/* 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";

declare var jQuery: any;
declare const APP_MODE: any;
declare const SERVER_ID: any;

@Injectable()
export class StatsRepo {

    private command: string  = 'cloudlinux-statistics';
    private chartCommand: string = 'cloudlinux-charts';

    constructor(private request: XHR) {}

  public getStatistics(params: {}) {
    if (typeof APP_MODE !== 'undefined'
      && typeof SERVER_ID !== 'undefined'
      && APP_MODE === 'TEST_MODE'
      && SERVER_ID
    ) { // for TEST MODE
      params['server_id'] = SERVER_ID;
    }
    return this.request.post({
      command: this.command,
      params: params,
    });
  }

    public history(user_id: number, params: {}) {
        params['id'] = user_id;
        return this.request.post({
            command: this.command,
            params: params,
        });
    }

    public chart(user_id: number, params: {}) {
        params['id'] = user_id;
        return this.request.post({
            command: this.chartCommand,
            params: params,
        }).then(data => {
            /*
            * browser and angular escapes quotes " in javascript
            * extract scrip tags and mount in to window
            * before angular and browser will get it*/
            data.chart = data.chart
              .replace(/&lt;/g, '<')
              .replace(/\r?\n|\r/g, ' ')
              .replace(/<script>(.*)<\/script>/g, (match, content, offset, string) => {
                  jQuery('body').append(jQuery('<script>').text(content));
                  return '';
              });
            return data;
        });

    }
}
