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

import Raven = require('raven-js');
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { NotificationsService } from '../services/notifiaction_service';
import { Loader } from './loader';


@Injectable()
export class XHR {
    request: Http;
    mainAction: string = 'CloudLinux.cgi?cgiaction=imunifyHandler';

    constructor(
        private http: Http,
        private notifictions: NotificationsService
    ) {
        this.request = http;
    }

    post(
        params: RequestParams
    ) {
        let headers = new Headers();
        headers.append('Content-type', 'application/json');
        let currentAction = this.mainAction;
        return new Promise((resolve, reject) => {
            this.request.post(currentAction, JSON.stringify(params), {headers: headers})
                .subscribe(
                    data => {
                        try {
                            const response = JSON.parse(data['_body']);
                            switch (response['result']) {
                                case 'success':
                                    resolve(response);
                                    break;
                                case 'error':
                                    reject(response);
                                    break;
                                default:
                                    break;
                            }
                        } catch (e) {
                             Raven.setExtraContext({
                                request: JSON.stringify(params),
                             });
                            if (e.hasOwnProperty('result')) {
                                this.notifictions.error(e['result'], e['messages']);
                            } else {
                                this.notifictions.error('Internal Error', 'See logs for details');
                                console.error(JSON.stringify(data));
                            }
                            reject(data);
                        }
                    },
                    err => {
                         Raven.setExtraContext({
                            request: JSON.stringify(params),
                         });
                        if (err.status === 502) {
                            try {
                                let errorObject = JSON.parse(err._body);
                                this.notifictions.error('Error', errorObject.result);
                                console.log('Error on server: ' + errorObject.result);
                            } catch (e) {
                            }
                        }
                        reject(err);
                    },
                );
        });
    }
}

interface RequestParams {
    command?: string;
    method?: string[];
    args?: string[];
    params?: Object;
    mockJson?: boolean;
}
