/* 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 { XHR } from '../utils/xhr';
import { AppState } from '../app.service';
import { User } from '../model/user';
import { Access } from '../services/access';
import { ViewModes } from '../services/view_modes';

@Injectable()
export class UsersRepo {

    private command: string  = 'cloudlinux-limits';
    private testMode: boolean = false;
    private accessService: Access;

    constructor(
        private request: XHR,
        private appState: AppState,
        private viewModeService: ViewModes
    ) {
        this.accessService = new Access(this.appState);
    }

    public getAllUsers() {
        return this.request.post({
            command: this.command,
            method: 'get',
        });
    }

    public getUser(user_id: number, user: User = null) {
        if (this.appState.get('isAdmin') && user && user.isReseller) {
            return this.getReseller(user.username);
        } else {
            let params = {'lve-id': user_id};
            return this.request.post({
                command: this.command,
                method: 'get',
                params: params,
            });
        }
    }

    public getReseller(resellerName: string) {
        let params = {'reseller-name': resellerName};
        return this.request.post({
            command: this.command,
            method: 'get',
            params: params,
        });
    }

    public loadReseller(resellerName: string): Promise<{user: User, response: any}> {
        return this.loadUser(null, resellerName);
    }

    public loadUser(userId: number, resellerName: string = null):
        Promise<{user: User, response: any}> {
        return new Promise((resolve, reject) => {
            let responsePromise = resellerName ?
                this.getReseller(resellerName) : this.getUser(userId);
            responsePromise.then((response) => {
                resolve({user: this.findUserInResponse(response, resellerName),
                    response: response});
            }).catch(error => {
                console.log(error);
                reject(error);
            });
        });
    }

    public findUserInResponse(response, resellerName: string = null): User {
        if (this.appState.get('isAdmin')) {
            this.viewModeService.concatResellerWithUser(response);
            this.viewModeService.detectUserTypes(response, ViewModes.availableModes);
        }
        if (resellerName) {
            response.users = response.users
              .filter(user => user.username === resellerName && user.isReseller)
        }
        for (let userData of response.users) {
          this.accessService.dropPermission(response, userData);
        }
        return new User(response, 0, this.appState, this);
    }

    public saveUser(user: User, params: {}) {
        if (this.appState.get('isAdmin') && user.isReseller) {
            params['reseller-name'] = user.username;
        } else {
            params['lve-id'] = user.id;
        }

        return this.request.post({
            command: this.command,
            method: 'set',
            params: params,
        });
    }

    public disableLimitsForReseller(resellerName: string) {
        if (this.appState.get('isAdmin')) {
            return this.request.post({
                command: this.command,
                method: 'disable-reseller-limits',
                params: {
                    'reseller-name': resellerName
                }
            });
        }
    }

    public enableLimitsForReseller(resellerName: string) {
        if (this.appState.get('isAdmin')) {
            return this.request.post({
                command: this.command,
                method: 'enable-reseller-limits',
                params: {
                    'reseller-name': resellerName
                }
            });
        }
    }
}
