Sync Integ to Master
[sdc.git] / catalog-ui / src / app / ng2 / components / layout / top-nav / top-nav.component.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import * as _ from "lodash";
22 import {Component, Inject, Input, Output, EventEmitter} from "@angular/core";
23 import {IHostedApplication, IUserProperties} from "app/models";
24 import {MenuItemGroup, MenuItem} from "app/utils";
25 import {UserService} from "../../../services/user.service";
26 import {SdcConfigToken, ISdcConfig} from "../../../config/sdc-config.config";
27 import {TranslateService} from "../../../shared/translator/translate.service";
28 import {PluginsConfiguration, Plugin} from "app/models";
29
30
31 declare const window:any;
32 @Component({
33     selector: 'top-nav',
34     templateUrl: './top-nav.component.html',
35     styleUrls:['./top-nav.component.less']
36 })
37 export class TopNavComponent {
38     @Input() public version:string;
39     @Input() public menuModel:Array<MenuItemGroup>;
40     @Input() public topLvlSelectedIndex:number;
41     @Input() public hideSearch:boolean;
42     @Input() public searchTerm:string;
43     @Input() public notificationIconCallback:Function;
44     @Output() public searchTermChange:EventEmitter<string> = new EventEmitter<string>();
45     emitSearchTerm(event:string) {
46         this.searchTermChange.emit(event);
47     }
48
49     public topLvlMenu:MenuItemGroup;
50     public user:IUserProperties;
51
52     constructor(private translateService:TranslateService,
53                 @Inject('$state') private $state:ng.ui.IStateService,
54                 private userService:UserService,
55                 @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) {
56         window.nav = this;
57     }
58
59     private _getTopLvlSelectedIndexByState = ():number => {
60         if (!this.topLvlMenu.menuItems) {
61             return 0;
62         }
63
64         let result = -1;
65
66         //set result to current state
67         this.topLvlMenu.menuItems.every((item:MenuItem, index:number)=> {
68             if (item.state === this.$state.current.name) {
69                 if (this.$state.current.name === 'plugins') {
70                     const pluginIdx = _.findIndex(PluginsConfiguration.plugins, (plugin: Plugin) => plugin.pluginStateUrl === this.$state.params.path);
71                     if (pluginIdx !== -1) {
72                         result = index + pluginIdx;
73                         return false;
74                     }
75                 } else {
76                     result = index;
77                     return false;
78                 }
79             }
80             return true;
81         });
82
83         //if it's a different state , checking previous state param
84         if (result === -1) {
85             this.topLvlMenu.menuItems.forEach((item:MenuItem, index:number)=> {
86                 if (item.state === this.$state.params['previousState']) {
87                     result = index;
88                 }
89             });
90         }
91
92         if (result === -1) {
93             result = 0;
94         }
95
96         return result;
97     };
98
99     ngOnChanges(changes) {
100         if (changes['menuModel']) {
101             console.log('menuModel was changed!');
102             this.generateMenu();
103         }
104     }
105
106     ngOnInit() {
107         console.log('Nav is init!', this.menuModel);
108         this.user = this.userService.getLoggedinUser();
109
110         this.translateService.languageChangedObservable.subscribe((lang) => {
111             let tmpArray: Array<MenuItem> = [
112                 new MenuItem(this.translateService.translate("TOP_MENU_HOME_BUTTON"), null, "dashboard", "goToState", null, null),
113                 new MenuItem(this.translateService.translate("TOP_MENU_CATALOG_BUTTON"), null, "catalog", "goToState", null, null)
114             ];
115
116             // Only designer can perform onboarding
117             if (this.user && this.user.role === 'DESIGNER') {
118                 tmpArray.push(new MenuItem(this.translateService.translate("TOP_MENU_ON_BOARD_BUTTON"), null, "onboardVendor", "goToState", null, null));
119                 _.each(this.sdcConfig.hostedApplications, (hostedApp: IHostedApplication) => {
120                     if (hostedApp.exists) {
121                         tmpArray.push(new MenuItem(hostedApp.navTitle, null, hostedApp.defaultState, "goToState", null, null));
122                     }
123                 });
124             }
125
126             // Adding plugins to top-nav only if they can be displayed for the current connected user role
127             _.each(PluginsConfiguration.plugins, (plugin: Plugin) => {
128                 if (plugin.pluginDisplayOptions["tab"] && (this.user && plugin.pluginDisplayOptions["tab"].displayRoles.includes(this.user.role))) {
129                     tmpArray.push(new MenuItem(plugin.pluginDisplayOptions["tab"].displayName, null, "plugins", "goToState", {path: plugin.pluginStateUrl}, null));
130                 }
131             });
132
133             this.topLvlMenu = new MenuItemGroup(0, tmpArray, true);
134             this.topLvlMenu.selectedIndex = isNaN(this.topLvlSelectedIndex) ? this._getTopLvlSelectedIndexByState() : this.topLvlSelectedIndex;
135
136             this.generateMenu();
137         });
138     }
139
140     generateMenu() {
141         if (this.menuModel && this.topLvlMenu && this.menuModel[0] !== this.topLvlMenu) {
142             this.menuModel.unshift(this.topLvlMenu);
143         }
144     }
145
146     goToState(state:string, params:Array<any>):Promise<boolean> {
147         return new Promise((resolve, reject) => {
148             this.$state.go(state, params && params.length > 0 ? [0] : undefined);
149             resolve(true);
150         });
151     }
152
153     menuItemClick(itemGroup:MenuItemGroup, item:MenuItem) {
154         itemGroup.itemClick = false;
155
156         let onSuccess = ():void => {
157             itemGroup.selectedIndex = itemGroup.menuItems.indexOf(item);
158         };
159         let onFailed = ():void => {
160         };
161
162         if (item.callback) {
163             (item.callback.apply(undefined, item.params)).then(onSuccess, onFailed);
164         } else {
165             this[item.action](item.state, item.params).then(onSuccess, onFailed);
166         }
167     }
168 }