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

import {
    Component, AfterViewInit, ViewChild, Injectable, EventEmitter, ElementRef, Input
} from '@angular/core';
import { Router, RouterOutlet } from '@angular/router';
import { SelectorRepo } from '../repository/selector_repo';
import { NodeJSInformation } from './model';
import { ModalDialog } from '../utils/ui-elements/modal-dialog/modal-dialog';
import { Message } from '../model/message';
import { ApplicationRow } from './application.row';
import { VersionRow } from './version.row';
import { AppService } from '../../selector/app.service';
import { Mixin } from '../utils/mixins/Mixin';
import { Filterable } from '../utils/mixins/Filterable';
import { BaseComponent } from '../utils/base_component';
import { UiFormElement } from '../utils/ui-elements/ui-form-element/ui-form-element';
import { LoaderSelector } from '../utils/loader';


@Component({
    selector: 'node-js',
    template: require('./index.component.html'),
    styles: [require('./index.component.less')],
    providers: [SelectorRepo, AppService]
})
@Injectable()
@Mixin([Filterable])
export class NodeJSIndexComponent extends BaseComponent implements AfterViewInit {

    public dataUpdated = new EventEmitter();
    public headerForConfirmationWindow: Message;

    @ViewChild('confirmationWindow') confirmationWindow: ModalDialog;
    @ViewChild(UiFormElement) uiFormElement: UiFormElement;
    @ViewChild(RouterOutlet) routerOutlet: RouterOutlet;

    @Input() highlightPhrase: string = '';

    private _selectorEnabled: boolean;

    public get data(): NodeJSInformation {
        return this.appService.fetchData();
    }

    constructor(
        private selectorRepo: SelectorRepo,
        private router: Router,
        private appService: AppService,
        public elementRef: ElementRef
    ) {
        super();
    }

    onDeactivateOutlet() {
        if (this.router.url.includes('options')
            && !this.router.url.includes('applications')) {
            this.router.navigate(['/options', {outlets: {nodejs: ['versions']}}]);
        }
    }

    ngAfterViewInit() {
        setTimeout(() => {
            this.router.navigate(['/options', {outlets: {nodejs: ['versions']}}]);
            this.loaderSelector = new LoaderSelector('#nodeJsSettings .group_content');
            this.loadDataFromServer();
        });
    }

    public set selectorEnabled(val: boolean) {
        this._selectorEnabled = val;
        if (typeof val !== 'undefined' && this.data.selector_enabled !== val) {
            let oldVal = this.data.selector_enabled;
            (async () => {
                try {
                    this.headerForConfirmationWindow = new Message(
                        'confirmationMessage.switchNodeJS',
                        {status: val ? 'enable' : 'disable'}
                    );
                    await this.confirmationWindow.open();
                    this.loading = true;
                    await this.appService.changeNodeJsStatus(val);
                } catch (e) {
                    // We pressed cancel button.
                    this._selectorEnabled = oldVal;
                } finally {
                    this.loading = false;
                }
            })();
        }
    }

    public get selectorEnabled(): boolean {
        return this._selectorEnabled;
    }

    public async loadDataFromServer() {
        try {
            this.loading = true;
            await this.appService.bindData();
            this.selectorEnabled = this.data.selector_enabled;
        } finally {
            this.loading = false;
        }
    }

}
