aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
blob: 8840afd79d4b3b7a3232bb4a2f5b4f133171d230 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

'use strict';
import * as _ from "lodash";
import {Component, IMainCategory, IGroup, IConfigStatuses, IAppMenu, IAppConfigurtaion, IUserProperties, ISubCategory, ICategoryBase} from "app/models";
import {EntityService, CacheService} from "app/services";
import {ComponentFactory, ResourceType, MenuHandler, ChangeLifecycleStateHandler} from "app/utils";
import {UserService} from "../../ng2/services/user.service";
import {ArchiveService} from "../../ng2/services/archive.service";
import { ICatalogSelector, CatalogSelectorTypes } from "../../models/catalogSelector";
import {IConfigStatus} from "../../models/app-config";

interface Checkboxes {
    componentTypes:Array<string>;
    resourceSubTypes:Array<string>;
}

interface CheckboxesFilter {
    // Types
    selectedComponentTypes:Array<string>;
    selectedResourceSubTypes:Array<string>;
    // Categories
    selectedCategoriesModel:Array<string>;
    // Statuses
    selectedStatuses:Array<Array<string>>;
}

interface Gui {
    isLoading:boolean;
    onComponentSubTypesClick:Function;
    onComponentTypeClick:Function;
    onCategoryClick:Function;
    onStatusClick:Function;
    changeFilterTerm:Function;
}

interface IFilterParams {
    components: string[];
    categories: string[];
    statuses: (string)[];
    order: [string, boolean];
    term: string;
    active: boolean;
}

interface ICategoriesMap {
    [key: string]: {
        category: ICategoryBase,
        parent: ICategoryBase
    }
}

export interface ICatalogViewModelScope extends ng.IScope {
    checkboxes:Checkboxes;
    checkboxesFilter:CheckboxesFilter;
    gui:Gui;

    categories:Array<IMainCategory>;
    confStatus:IConfigStatuses;
    sdcMenu:IAppMenu;
    catalogFilterdItems:Array<Component>;
    expandedSection:Array<string>;
    actionStrategy:any;
    user:IUserProperties;
    catalogMenuItem:any;
    version:string;
    sortBy:string;
    reverse:boolean;
    vfcmtType:string;

    //this is for UI paging
    numberOfItemToDisplay:number;
    isAllItemDisplay:boolean;
    catalogFilteredItemsNum:number;
    changeLifecycleState(entity:any, state:string):void;
    sectionClick (section:string):void;
    order(sortBy:string):void;
    getElementFoundTitle(num:number):string;
    goToComponent(component:Component):void;
    raiseNumberOfElementToDisplay():void;

    selectedCatalogItem: ICatalogSelector;
    catalogSelectorItems: Array<ICatalogSelector>;
    showCatalogSelector: boolean;
    catalogAllItems:Array<Component>; /* fake data */
    elementFoundTitle: string;
    elementTypeTitle: string;

    selectLeftSwitchItem (item: ICatalogSelector): void;
}

export class CatalogViewModel {
    static '$inject' = [
        '$scope',
        '$filter',
        'Sdc.Services.EntityService',
        'sdcConfig',
        'sdcMenu',
        '$state',
        '$q',
        'UserServiceNg2',
        'Sdc.Services.CacheService',
        'ComponentFactory',
        'ChangeLifecycleStateHandler',
        'MenuHandler',
        'ArchiveServiceNg2'
    ];

    private defaultFilterParams:IFilterParams = {
        components: [],
        categories: [],
        statuses: [],
        order: ['lastUpdateDate', true],
        term: '',
        active: true
    };
    private categoriesMap:ICategoriesMap;

    constructor(private $scope:ICatalogViewModelScope,
                private $filter:ng.IFilterService,
                private EntityService:EntityService,
                private sdcConfig:IAppConfigurtaion,
                private sdcMenu:IAppMenu,
                private $state:ng.ui.IStateService,
                private $q:ng.IQService,
                private userService:UserService,
                private cacheService:CacheService,
                private ComponentFactory:ComponentFactory,
                private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
                private MenuHandler:MenuHandler,
                private ArchiveService:ArchiveService
            ) {


        this.initLeftSwitch();
        this.initScopeMembers();
        this.loadFilterParams(); 
        this.initCatalogData(); // Async task to get catalog from server.
        this.initScopeMethods();
    }


    private initLeftSwitch = ():void => {
        this.$scope.showCatalogSelector = false;

        this.$scope.catalogSelectorItems = [
            {value: CatalogSelectorTypes.Active, title: "Active Items", header: "Active"},
            {value: CatalogSelectorTypes.Archive, title: "Archive", header: "Archived"}
        ];
        // set active items is default
        this.$scope.selectedCatalogItem = this.$scope.catalogSelectorItems[0];
    };

    private initCatalogData = ():void => {
        if(this.$scope.selectedCatalogItem.value === CatalogSelectorTypes.Archive){
            this.getArchiveCatalogItems();
        } else {
            this.getActiveCatalogItems();
        }
    };

    private initScopeMembers = ():void => {
        // Gui init
        this.$scope.gui = <Gui>{};
        this.$scope.numberOfItemToDisplay = 0;
        this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')).map((cat) => <IMainCategory>cat);
        this.$scope.sdcMenu = this.sdcMenu;
        this.$scope.confStatus = this.sdcMenu.statuses;
        this.$scope.expandedSection = ["type", "category", "status"];
        this.$scope.user = this.userService.getLoggedinUser();
        this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;

        // Checklist init
        this.$scope.checkboxes = <Checkboxes>{};
        this.$scope.checkboxes.componentTypes = ['Resource', 'Service'];
        this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CR', 'PNF', 'CP', 'VL'];
        this.categoriesMap = this.initCategoriesMap();

        this.initCheckboxesFilter();
        this.$scope.version = this.cacheService.get('version');
        this.$scope.sortBy = 'lastUpdateDate';
        this.$scope.reverse = true;

    };

    private initCheckboxesFilter() {
        // Checkboxes filter init
        this.$scope.checkboxesFilter = <CheckboxesFilter>{};
        this.$scope.checkboxesFilter.selectedComponentTypes = [];
        this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
        this.$scope.checkboxesFilter.selectedCategoriesModel = [];
        this.$scope.checkboxesFilter.selectedStatuses = [];
    }

    private initCategoriesMap(categoriesList?:(ICategoryBase)[], parentCategory:ICategoryBase=null): ICategoriesMap {
        categoriesList = (categoriesList) ? categoriesList : this.$scope.categories;

        // Init categories map
        return categoriesList.reduce((acc, cat) => {
            acc[cat.uniqueId] = {
                category: cat,
                parent: parentCategory
            };
            const catChildren = ((<IMainCategory>cat).subcategories)
                ? (<IMainCategory>cat).subcategories
                : (((<ISubCategory>cat).groupings)
                    ? (<ISubCategory>cat).groupings
                    : null);
            if (catChildren) {
                Object.assign(acc, this.initCategoriesMap(catChildren, cat));
            }
            return acc;
        }, <ICategoriesMap>{});
    }

    private initScopeMethods = ():void => {
        this.$scope.selectLeftSwitchItem = (item: ICatalogSelector): void => {

            if (this.$scope.selectedCatalogItem.value !== item.value) {
                this.$scope.selectedCatalogItem = item;
                switch (item.value) {
                    case CatalogSelectorTypes.Active:
                        this.getActiveCatalogItems(true);
                        break;

                    case CatalogSelectorTypes.Archive:
                        this.getArchiveCatalogItems(true);
                        break;
                }
                this.changeFilterParams({active: (item.value === CatalogSelectorTypes.Active)})
            }
        };

        this.$scope.sectionClick = (section: string): void => {
            let index: number = this.$scope.expandedSection.indexOf(section);
            if (index !== -1) {
                this.$scope.expandedSection.splice(index, 1);
            } else {
                this.$scope.expandedSection.push(section);
            }
        };


        this.$scope.order = (sortBy: string): void => {//default sort by descending last update. default for alphabetical = ascending
            this.changeFilterParams({
                order: (this.$scope.filterParams.order[0] === sortBy)
                    ? [sortBy, !this.$scope.filterParams.order[1]]
                    : [sortBy, sortBy === 'lastUpdateDate']
            });
        };


        this.$scope.goToComponent = (component: Component): void => {
            this.$scope.gui.isLoading = true;
            this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()});
        };


        // Will print the number of elements found in catalog
        this.$scope.getNumOfElements = (num:number):string => {
            if (!num || num === 0) {
                return `No <b>${this.$scope.selectedCatalogItem.header}</b> Elements found`;
            } else if (num === 1) {
                return `1 <b>${this.$scope.selectedCatalogItem.header}</b> Element found`;
            } else {
                return num + ` <b>${this.$scope.selectedCatalogItem.header}</b> Elements found`;
            }
        };

        /**
         * Select | unselect sub resource when resource is clicked | unclicked.
         * @param type
         */
        this.$scope.gui.onComponentTypeClick = (compType: string, checked?: boolean): void => {
            let components = angular.copy(this.$scope.filterParams.components);
            const compIdx = components.indexOf(compType);
            checked = (checked !== undefined) ? checked : compIdx === -1;
            if (checked && compIdx === -1) {
                components.push(compType);
                components = this.cleanSubsFromList(components);
            } else if (!checked && compIdx !== -1) {
                components.splice(compIdx, 1);
            }
            this.changeFilterParams({
                components: components
            });
        };

        /**
         * Selecting | unselect resources when sub resource is clicked | unclicked.
         */
        this.$scope.gui.onComponentSubTypesClick = (compSubType: string, compType: string, checked?: boolean): void => {
            const componentSubTypesCheckboxes = this.$scope.checkboxes[compType.toLowerCase() + 'SubTypes'];
            if (componentSubTypesCheckboxes) {
                let components = angular.copy(this.$scope.filterParams.components);
                let componentSubTypes = components.filter((st) => st.startsWith(compType + '.'));

                const compSubTypeValue = compType + '.' + compSubType;
                const compSubTypeValueIdx = components.indexOf(compSubTypeValue);
                checked = (checked !== undefined) ? checked : compSubTypeValueIdx === -1;
                if (checked && compSubTypeValueIdx === -1) {
                    components.push(compSubTypeValue);
                    componentSubTypes.push(compSubTypeValue);

                    // if all sub types are checked, then check the main component type
                    if (componentSubTypes.length === componentSubTypesCheckboxes.length) {
                        this.$scope.gui.onComponentTypeClick(compType, true);
                        return;
                    }
                } else if (!checked) {
                    const compIdx = components.indexOf(compType);
                    // if sub type exists, then remove it
                    if (compSubTypeValueIdx !== -1) {
                        components.splice(compSubTypeValueIdx, 1);
                    }
                    // else, if sub type doesn't exists, but its parent main component type exists,
                    // then remove the main type and push all sub types except the current
                    else if (compIdx !== -1) {
                        components.splice(compIdx, 1);
                        componentSubTypesCheckboxes.forEach((st) => {
                            if (st !== compSubType) {
                                components.push(compType + '.' + st);
                            }
                        });
                    }
                }

                this.changeFilterParams({
                    components
                });
            }
        };

        this.$scope.gui.onCategoryClick = (category: ICategoryBase, checked?: boolean): void => {
            let categories: string[] = angular.copy(this.$scope.filterParams.categories);
            let parentCategory: ICategoryBase = this.categoriesMap[category.uniqueId].parent;

            // add the category to selected categories list
            const categoryIdx = categories.indexOf(category.uniqueId);
            checked = (checked !== undefined) ? checked : categoryIdx === -1;
            if (checked && categoryIdx === -1) {
                categories.push(category.uniqueId);

                // check if all parent category children are checked, then check the parent category
                if (parentCategory) {
                    if (this.getParentCategoryChildren(parentCategory).every((ch) => categories.indexOf(ch.uniqueId) !== -1)) {
                        this.$scope.gui.onCategoryClick(parentCategory, true);
                        return;
                    }
                }

                categories = this.cleanSubsFromList(categories);
            } else if (!checked) {
                // if category exists, then remove it
                if (categoryIdx !== -1) {
                    categories.splice(categoryIdx, 1);
                }
                // else, if category doesn't exists, but one of its parent categories exists,
                // then remove that parent category and push all its children categories except the current
                else {
                    let prevParentCategory: ICategoryBase = category;
                    let additionalCategories: string[] = [];
                    while (parentCategory) {
                        // add parent category children to list for replacing the parent category (if will be found later)
                        additionalCategories = additionalCategories.concat(
                            this.getParentCategoryChildren(parentCategory)
                                .filter((ch) => ch.uniqueId !== prevParentCategory.uniqueId)
                                .map((ch) => ch.uniqueId));

                        const parentCategoryIdx = categories.indexOf(parentCategory.uniqueId);
                        if (parentCategoryIdx !== -1) {
                            categories.splice(parentCategoryIdx, 1);
                            categories = categories.concat(additionalCategories);
                            break;
                        } else {
                            prevParentCategory = parentCategory;
                            parentCategory = this.categoriesMap[parentCategory.uniqueId].parent;
                        }
                    }
                }
            }

            this.changeFilterParams({
                categories
            });
        };

        this.$scope.gui.onStatusClick = (statusKey: string, status: IConfigStatus, checked?: boolean) => {
            const statuses = angular.copy(this.$scope.filterParams.statuses);

            // add the status key to selected statuses list
            const statusIdx = statuses.indexOf(statusKey);
            checked = (checked !== undefined) ? checked : statusIdx === -1;
            if (checked && statusIdx === -1) {
                statuses.push(statusKey);
            } else if (!checked && statusIdx !== -1) {
                statuses.splice(statusIdx, 1);
            }

            this.changeFilterParams({
                statuses
            });
        };

        this.$scope.gui.changeFilterTerm = (filterTerm: string) => {
            this.changeFilterParams({
                term: filterTerm
            });
        };

        this.$scope.raiseNumberOfElementToDisplay = (): void => {
            this.$scope.numberOfItemToDisplay = this.$scope.numberOfItemToDisplay + 35;
            if (this.$scope.catalogFilterdItems) {
                this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
            }
        };

    }

    private getAllCategoryChildrenIdsFlat(category:ICategoryBase) {
        let catChildrenIds = [];
        if ((<IMainCategory>category).subcategories) {
            catChildrenIds = (<IMainCategory>category).subcategories.reduce((acc, scat) => {
                    return acc.concat(this.getAllCategoryChildrenIdsFlat(scat));
                }, (<IMainCategory>category).subcategories.map((scat) => scat.uniqueId));
        }
        else if ((<ISubCategory>category).groupings) {
            catChildrenIds = (<ISubCategory>category).groupings.map((g) => g.uniqueId);
        }
        return catChildrenIds;
    }

    private getParentCategoryChildren(parentCategory:ICategoryBase): ICategoryBase[] {
        if ((<IMainCategory>parentCategory).subcategories) {
            return (<IMainCategory>parentCategory).subcategories;
        } else if ((<ISubCategory>parentCategory).groupings) {
            return (<ISubCategory>parentCategory).groupings;
        }
        return [];
    }

    private cleanSubsFromList(list:Array<string>, delimiter:string='.', removeSubsList?:Array<string>) {
        let curRemoveSubsList = (removeSubsList || list).slice().sort();  // by default remove any children of any item in list
        while (curRemoveSubsList.length) {
            const curRemoveSubItem = curRemoveSubsList.shift();
            const removeSubListFilter = (x) => !x.startsWith(curRemoveSubItem + delimiter);
            list = list.filter(removeSubListFilter);
            curRemoveSubsList = curRemoveSubsList.filter(removeSubListFilter);
        }
        return list;
    }

    private applyFilterParamsToView(filterParams:IFilterParams) {
        // reset checkboxes filter
        this.initCheckboxesFilter();

        this.applyFilterParamsComponents(filterParams);
        this.applyFilterParamsCategories(filterParams);
        this.applyFilterParamsStatuses(filterParams);
        this.applyFilterParamsOrder(filterParams);
        this.applyFilterParamsTerm(filterParams);
    }

    private applyFilterParamsComponents(filterParams:IFilterParams) {
        const componentList = [];
        const componentSubTypesLists = {};
        filterParams.components.forEach((compStr) => {
            const compWithSub = compStr.split('.', 2);
            const mainComp = compWithSub[0];
            const subComp = compWithSub[1];
            if (!subComp) {  // main component type
                componentList.push(mainComp);

                // if component type has sub types list, then add all component sub types
                const checkboxesSubTypeKey = mainComp.toLowerCase() + 'SubTypes';
                if (this.$scope.checkboxes.hasOwnProperty(checkboxesSubTypeKey)) {
                    componentSubTypesLists[mainComp] = angular.copy(this.$scope.checkboxes[checkboxesSubTypeKey]);
                }
            } else {  // sub component type
                // init component sub types list
                if (!componentSubTypesLists.hasOwnProperty(mainComp)) {
                    componentSubTypesLists[mainComp] = [];
                }
                // add sub type to list if not exist
                if (componentSubTypesLists[mainComp].indexOf(subComp) === -1) {
                    componentSubTypesLists[mainComp].push(subComp);
                }
            }
        });
        this.$scope.checkboxesFilter.selectedComponentTypes = componentList;
        Object.keys(componentSubTypesLists).forEach((tKey) => {
            const compSelectedSubTypeKey = 'selected' + tKey + 'SubTypes';
            if (this.$scope.checkboxesFilter.hasOwnProperty(compSelectedSubTypeKey)) {
                this.$scope.checkboxesFilter[compSelectedSubTypeKey] = componentSubTypesLists[tKey];
            }
        });

        let selectedCatalogIndex = filterParams.active ? CatalogSelectorTypes.Active : CatalogSelectorTypes.Archive;
        this.$scope.selectedCatalogItem = this.$scope.catalogSelectorItems[selectedCatalogIndex];
        
    }

    private applyFilterParamsCategories(filterParams:IFilterParams) {
        this.$scope.checkboxesFilter.selectedCategoriesModel = filterParams.categories.reduce((acc, c) => {
            acc.push(c);
            const cat = this.categoriesMap[c].category;
            if (cat) {
                acc = acc.concat(this.getAllCategoryChildrenIdsFlat(cat));
            }
            return acc;
        }, []);
    }

    private getActiveCatalogItems(forceReload?: boolean): void {

        if (forceReload || this.componentShouldReload()) {
            this.$scope.gui.isLoading = true;
            let onSuccess = (followedResponse:Array<Component>):void => {
                this.updateCatalogItems(followedResponse);
                this.$scope.gui.isLoading = false;
                this.cacheService.set('breadcrumbsComponentsState', this.$state.current.name);  //catalog
                this.cacheService.set('breadcrumbsComponents', followedResponse);
            };

            let onError = ():void => {
                console.info('Failed to load catalog CatalogViewModel::getActiveCatalogItems');
                this.$scope.gui.isLoading = false;
            };
            this.EntityService.getCatalog().then(onSuccess, onError);
        } else {
            let cachedComponents = this.cacheService.get('breadcrumbsComponents');
            this.updateCatalogItems(cachedComponents);
        }
    }

    private getArchiveCatalogItems(forceReload?: boolean): void {
        if(forceReload || !this.cacheService.contains("archiveComponents")) {
            this.$scope.gui.isLoading = true;
            let onSuccess = (followedResponse:Array<Component>):void => {
                this.cacheService.set("archiveComponents", followedResponse);
                this.updateCatalogItems(followedResponse);
                this.$scope.gui.isLoading = false;
            };
    
            let onError = ():void => {
                console.info('Failed to load catalog CatalogViewModel::getArchiveCatalogItems');
                this.$scope.gui.isLoading = false;
            };
    
            this.ArchiveService.getArchiveCatalog().subscribe(onSuccess, onError);
        } else {
            let archiveCache = this.cacheService.get("archiveComponents");
            this.updateCatalogItems(archiveCache);
        }

    }

    private updateCatalogItems = (items:Array<Component>):void => {
        this.$scope.catalogFilterdItems = items;
        this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
        this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories'));
    }

    private componentShouldReload = ():boolean => {
        let breadcrumbsValid: boolean = (this.$state.current.name === this.cacheService.get('breadcrumbsComponentsState') && this.cacheService.contains('breadcrumbsComponents'));
        return !breadcrumbsValid || this.isDefaultFilter();
    }

    private isDefaultFilter = (): boolean => {
        return angular.equals(this.defaultFilterParams, this.$scope.filterParams);
    }

    private applyFilterParamsStatuses(filterParams: IFilterParams) {
        this.$scope.checkboxesFilter.selectedStatuses = filterParams.statuses.reduce((acc, stKey:string) => {
            const status = this.$scope.confStatus[stKey];
            if (status) {
                acc.push(status.values);
            }
            return acc;
        }, []);
    }

    private applyFilterParamsOrder(filterParams: IFilterParams) {
        this.$scope.sortBy = filterParams.order[0];
        this.$scope.reverse = filterParams.order[1];
    }

    private applyFilterParamsTerm(filterParams: IFilterParams) {
        this.$scope.search = {
            filterTerm: filterParams.term
        };
    }

    private loadFilterParams() {
        const params = this.$state.params;
        this.$scope.filterParams = angular.copy(this.defaultFilterParams);
        Object.keys(params).forEach((k) => {
            if (!angular.isUndefined(params[k])) {
                let newVal;
                let filterKey = k.substr('filter.'.length);
                switch (k) {
                    case 'filter.components':
                    case 'filter.categories':
                        newVal = _.uniq(params[k].split(','));
                        newVal = this.cleanSubsFromList(newVal);
                        break;
                    case 'filter.statuses':
                        newVal = _.uniq(params[k].split(','));
                        break;
                    case 'filter.order':
                        newVal = params[k].startsWith('-') ? [params[k].substr(1), true] : [params[k], false];
                        break;
                    case 'filter.term':
                        newVal = params[k];
                        break;
                    case 'filter.active':
                        newVal = (params[k] === "true" || params[k] === true);
                        break;
                    default:
                        // unknown filter key
                        filterKey = null;
                }
                if (filterKey) {
                    this.$scope.filterParams[filterKey] = newVal;
                }
            }
        });
        // re-set filter params with valid values
        this.applyFilterParamsToView(this.$scope.filterParams);

    }

    private changeFilterParams(changedFilterParams) {
        const newParams = {};
        Object.keys(changedFilterParams).forEach((k) => {
            let newVal;
            switch (k) {
                case 'components':
                case 'categories':
                case 'statuses':
                    newVal = changedFilterParams[k] && changedFilterParams[k].length ? changedFilterParams[k].join(',') : null;
                    break;
                case 'order':
                    newVal = (changedFilterParams[k][1] ? '-' : '') + changedFilterParams[k][0];
                    break;
                case 'term':
                    newVal = changedFilterParams[k] ? changedFilterParams[k] : null;
                    break;
                case 'active':
                    newVal = changedFilterParams[k];
                    break;
                default:
                    return;
            }
            this.$scope.filterParams[k] = changedFilterParams[k];
            newParams['filter.' + k] = newVal;
        });
        this.$state.go('.', newParams, {location: 'replace', notify: false}).then(() => {
            this.applyFilterParamsToView(this.$scope.filterParams);
        });
    }
}