1/**
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/** This class defines and/or implements the common properties and methods
18 * used among menus.
19 */
20import { AppService } from '../appservice';
21import { MatSnackBar } from '@angular/material';
22import moment from 'moment-timezone';
23
24
25export abstract class MenuBaseClass {
26  count = -1;
27
28  loading = false;
29  pageSizeOptions = [20, 50, 100, 200];
30  pageSize = 100;
31  pageIndex = 0;
32
33  protected constructor(private appService: AppService,
34                        public snackBar: MatSnackBar) {
35    this.appService.closeSideNav();
36    this.snackBar.dismiss();
37  }
38
39  /** Returns an Observable which handles a response of count API.
40   * @param additionalOperations A list of lambda functions.
41   */
42  getDefaultCountObservable(additionalOperations: any[] = []) {
43    return {
44      next: (response) => {
45        this.count = response.count;
46        for (const operation of additionalOperations) {
47          operation(response);
48        }
49      },
50      error: (error) => this.showSnackbar(`[${error.status}] ${error.name}`)
51    };
52  }
53
54  getRelativeTime(timeString) {
55    return (moment.tz(timeString, 'YYYY-MM-DDThh:mm:ss', 'UTC').isValid() ?
56      moment.tz(timeString, 'YYYY-MM-DDThh:mm:ss', 'UTC').fromNow() : '---');
57  }
58
59  /** Checks whether timeString is expired from current time. */
60  isExpired(timeString, hours=72) {
61    let currentTime = moment.tz(timeString, 'YYYY-MM-DDThh:mm:ss', 'UTC');
62    if (!currentTime.isValid()) { return false; }
63
64    let diff = moment().diff(currentTime);
65    let duration = moment.duration(diff);
66    return duration.asHours() > hours;
67  }
68
69  /** Displays a snackbar notification. */
70  showSnackbar(message = 'Error', duration = 5000) {
71    this.loading = false;
72    this.snackBar.open(message, 'DISMISS', {duration});
73  }
74
75  /** Displays a side nav window and lists all properties of selected entity. */
76  onShowDetailsClicked(entity) {
77    this.appService.showDetails(entity);
78  }
79}
80