/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */

import { Component, ViewContainerRef, ViewChild } from '@angular/core';
import { AppState } from './app.service';
import { BaseComponent } from './utils/base_component';
import { ConfigRepo } from './repository/config_repo';
import { PingRepo } from './repository/ping_repo';
import { XHR } from './utils/xhr';
import { NotificationsService } from './services/notifiaction_service';
import { OWNER_ADMIN, OWNER_RESELLER, OWNER_USER } from './services/access';
import { NavigationStart, Router, RouterOutlet } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { DEFAULT_LANGUAGE } from './services/constants';
import { Panel } from './utils/panel';
import { PlatformLocation } from '@angular/common';
import { LoadingBarService } from '@ngx-loading-bar/core';
import { InstanceInjector } from './services/instance-injector';
import * as moment from 'moment';

declare var imagePath: any;
declare const panelName: any;
declare const panelVersion: any;
declare const userType: any;
declare const userName: any;
declare const currentLanguage: any;

@Component({
    selector: 'lvemanager',
    template: require('../templates/app.html'),
    providers: [NotificationsService, XHR, PingRepo],
    styles: [require('../styles/app.component.less')]
})
export class App extends BaseComponent {
    @ViewChild(RouterOutlet) public routerOutlet: RouterOutlet;
    @ViewChild('tabHeader') public tabHeader: any;
    public tabs = [];
    public isAvailableElementForCurrentPanel = {
        'nodejs_selector': false
    };

    constructor(
        public appState: AppState,
        private configRepo: ConfigRepo,
        public viewRef: ViewContainerRef,
        private translate: TranslateService,
        private router: Router,
        private platformLocation: PlatformLocation,
        public loadingBar: LoadingBarService
    ) {
        super();

        InstanceInjector.loadingBarServiceInstance = loadingBar;

        this.appState.set('imagePath', imagePath);
        this.appState.set('panelName', panelName);
        this.appState.set('userType', userType);
        this.appState.set('userName', userName);
        this.appState.set('currentLanguage', currentLanguage);

        this.appState.set('isAdmin',    userType === OWNER_ADMIN);
        this.appState.set('isReseller', userType === OWNER_RESELLER);
        this.appState.set('isUser', userType === OWNER_USER);

        this.appState.set('historyLength', 0);
        this.appState.set('menuLoader', false);

        this.defineAvailabilityOfElements();

        this.configRepo.getConfig();
        this.configRepo.getAdmins();
        this.tabs = this.getTabs();
        this.setupLanguages();

        this.router.events.subscribe((val) => {
            if (val instanceof NavigationStart) {
                this.platformLocation.replaceState({page: this.appState.get('historyLength')}, '', '');
                this.appState.set('historyLength', this.appState.get('historyLength') + 1);
            }
        });

        this.platformLocation.onPopState((event: any) => {
              if (event.state) {
                  this.appState.set('historyLength', event.state.page - 1); // 1 - will be returned on route event
              }
        });
    }

    ngOnInit() {
        // console.log('Application work!!!@@@');
    }

    /**
     * Define availability of elements for current panel.
     */
    defineAvailabilityOfElements() {
        // Define availability of Node.js selector.
        this.isAvailableElementForCurrentPanel['nodejs_selector']
            = ![Panel.PLESK].includes(this.appState.get('panelName'));

        this.appState.set(
            'isAvailableElementForCurrentPanel',
            this.isAvailableElementForCurrentPanel
        );
    }

    getTabs() {
      let tabList = [];
      tabList.push({link: 'current', altLink: '/', text: 'Current Usage'});
      if (userType === 'reseller') {
        tabList.push({link: 'historical', text: 'Historical Usage'});
      }
      tabList.push({link: 'users', text: 'Users'});
      tabList.push({link: 'stats', text: 'Statistics'});
      tabList.push({link: 'options', text: 'Options'});
      tabList.push({link: 'packages', text: 'Packages'});
      if (userType === 'admin') {
        tabList.push({link: 'selector', text: 'Selector'});
      }
      // if (userType === 'admin' && panelName === 'Cpanel') {
      //   tabList.push({link: 'incidents', text: 'Security Sensor'});
      // }
      return tabList;
    }

    public isActive(path) {
        if (path === '/'){
            return window.location.hash === '#/';
        }
        return window.location.hash.indexOf(path) > -1;
    }

    private setupLanguages() {
        this.translate.addLangs([DEFAULT_LANGUAGE]);
        this.translate.setDefaultLang(DEFAULT_LANGUAGE);

        let languageCode = currentLanguage || DEFAULT_LANGUAGE;
        if (!currentLanguage.includes('-')) {
            languageCode = languageCode + '-' + languageCode.toUpperCase();
        }

        if (currentLanguage !== DEFAULT_LANGUAGE) {
            let language = currentLanguage.substr(0, 2);
            this.translate.addLangs([language]);
            this.translate.use(language);
        }

        moment.locale(languageCode);
    }

    public notification_options = {
        timeOut: 5000,
        lastOnBottom: true,
        clickToClose: true,
        maxLength: 0,
        maxStack: 7,
        showProgressBar: false,
        pauseOnHover: true,
        preventDuplicates: false,
        preventLastDuplicates: 'visible',
        rtl: false,
        animate: true,
        open: false
    };
}

export const APP_PROVIDERS = [
    AppState
];
