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

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { BaseComponent } from '../utils/base_component';
import { AppState } from '../app.service';
import { XHR } from '../utils/xhr';
import {
    STATUS_FIREWALL_NOT_INSTALLED, STATUS_PLUGIN_INSTALLED,
    STATUS_SERVICE_DISABLED
} from './imunify-status.component';
import { LoaderSelector } from '../utils/loader';


@Injectable()
export class ImunifyGuard extends BaseComponent implements CanActivate {
    public constructor(
        private request: XHR,
        private router: Router,
        public appState: AppState,
    ) {
        super();
        this.loaderSelector = new LoaderSelector('.main_content_block');
    }

    public async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (state.url !== '/incidents') {
            return true;
        }

        this.loading = true;
        try {
            let response = await this.getImunifyStatus();
            if (response['cpanel']) {
                this.appState.set('imunify-status', STATUS_PLUGIN_INSTALLED);
                this.router.navigate(['incidents/status']);
                return false;
            } else if (!response['firewall']) {
                this.appState.set('imunify-status', STATUS_FIREWALL_NOT_INSTALLED);
                this.router.navigate(['incidents/status']);
                return false;
            } else if (!response['enabled']) {
                this.appState.set('imunify-status', STATUS_SERVICE_DISABLED);
                this.router.navigate(['incidents/status']);
                return false;
            }
        } finally {
            this.loading = false;
        }

        return true;
    }

    public async getImunifyStatus() {
        try {
            let response = await this.request.post({
                'handler': 'imunify',
                'command': 'imunifyStatus'
            });
            return response['data'];
        } catch (e) {
            return {
                'cpanel': false,
                'firewall': false,
            };
        }
    }
}
