/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */
import { Component, ViewChild, OnDestroy,
    QueryList, ViewChildren, ElementRef, Input } from '@angular/core';
import { CagefsRepo } from '../repository/cagefs_repo';
import { Message } from '../model/message';
import { KEY_CONFIRMATION_MESSAGE } from '../services/constants';
import { AppState } from '../app.service';
import { ModalWindow } from '../utils/ui-elements/modal-dialog/modal-window';
import { FeSwitcher } from '../utils/ui-elements/form-elements/fe-switcher/fe-switcher';
import { FeButton } from '../utils/ui-elements/form-elements/fe-button/fe-button';
import { Filterable } from '../utils/mixins/Filterable';
import { BaseComponent } from '../utils/base_component';
import { Mixin } from '../utils/mixins/Mixin';
import { LoaderSelector } from '../utils/loader';

@Component({
    selector: 'cagefs-plugin',
    template: require('./cagefs.component.html'),
    styles: [
        require('./cagefs.component.less')
    ],
    providers: [CagefsRepo]
})
@Mixin([Filterable])
export class CagefsComponent extends BaseComponent implements OnDestroy {

    @ViewChild('toggleCagefs') public toggleCagefs: ModalWindow;
    @ViewChildren(FeButton) feButtonList: QueryList<FeButton>;
    @ViewChildren(FeSwitcher) feSwitcherList: QueryList<FeSwitcher>;

    @Input() highlightPhrase: string = '';

    public currentConfirmationMessage: Message;
    public skeletonStatus: boolean = false;
    public cagefsMode: string = '';
    public cagefsProcess: string = '';

    private _cagefsStatus: string = '';

    private updateTimer: number = 0;

    constructor (private cagefsRepo: CagefsRepo,
                 public appState: AppState,
                 public elementRef: ElementRef) {
        super();
        if (!appState.get('isAdmin')) {
            return;
        }
        this.loaderSelector = new LoaderSelector('.options_component');
        this.updateStatus();
    }

    public updateStatus() {
        if (this.loading) {
            return;
        }
        this.cagefsRepo.cageFsStatus().then(
            (data) => {
                if (this.loading) {
                    return;
                }
                this.cagefsStatus = data.response.status;
                this.skeletonStatus = data.response.skeleton;
                this.cagefsMode = data.response.mode;
                this.cagefsProcess = data.response.process;
                if (this.cagefsProcess !== '' && !this.updateTimer) {
                    this.updateTimer = setInterval(this.updateStatus.bind(this), 10000);
                }
                if (this.cagefsProcess === '' && this.updateTimer){
                    clearInterval(this.updateTimer);
                    this.updateTimer = 0;
                }
            }
        );
    }

    public get cagefsStatus(): string {
        return this._cagefsStatus;
    }

    public set cagefsStatus(value: string) {
        this._cagefsStatus = value.toLowerCase();
    }

    public get cagefsAction(): string {
        return this.cagefsStatus == 'disabled' ? 'enable' : 'disable';
    }

    updateCageFsSkeleton () {
        this.loading = true;
        this.cagefsRepo.cagefsUpdateSkeleton().then((data) => {
            this.loading = false;
            this.cagefsProcess = data.response;
            this.updateStatus();
        }).catch(() => {
            this.loading = false;
        });
    }

    initCageFs() {
        this.loading = true;
        this.cagefsRepo.initCageFs().then((data) => {
            this.loading = false;
            this.cagefsProcess = 'init';
            this.updateStatus();
        }).catch(() => {
            this.loading = false;
        });
    }

    toggleCageFsStatus (event) {
        this.currentConfirmationMessage = this.getConfirmationMessage();
        this.toggleCagefs.open().then(
            () => {
                let command = this.cagefsStatus == 'enabled' ? 'disable-cagefs' : 'enable-cagefs';
                this.loading = true;
                this.cagefsRepo.cageFsRun(command).then((data) => {
                    this.cagefsStatus = data.response.toLowerCase().includes('enabled')
                        ? 'enabled'
                        : 'disabled';
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                });
            }
        ).catch(()=>{});
        event.stopPropagation();
        event.preventDefault();
    }

    toggleCageFsMode () {
        this.loading = true;
        this.cagefsRepo.cageFsRun('toggle-mode').then((data) => {
            this.cagefsMode = data.response.includes('Enable') ? 'enabled' : 'disabled';
            this.loading = false;
        }).catch(() => {
            this.loading = false;
        });
    }

    public getConfirmationMessage(type='default'): Message {
        const context = {
            'default': {},
        };
        let curType = context.hasOwnProperty(type) ? type : 'default';
        return new Message(KEY_CONFIRMATION_MESSAGE + '.' + curType, context[curType]);
    }

    ngOnDestroy() {
        if (this.updateTimer) {
            clearInterval(this.updateTimer);
        }
    }

}
