import pako = require('pako');
import { DataPoint } from './DataPoint';
import { CloudwatchDataPoint } from './CloudwatchDataPoint';
import { FastlyDataPoint } from './FastlyDataPoint';
import { TherapistDataPoint } from './TherapistDataPoint';

export class SensuEvent {
  dataPoints: DataPoint[] = [];

  constructor(encodedData: string) {
    const data = JSON.parse(new Buffer(encodedData, 'base64').toString('ascii'));
    if (data.check.status === 0) {
      this.populateDataPoints(data.check);
    } else {
      console.log("Got non-zero status code on check: ", data.check.output, data.client.name, data.check.name)
    }
  }

  populateDataPoints(checkData: any): void {
    try {      
      let data: any;
      let zippedData = new Buffer(checkData.output, 'base64');

      try {
        data = JSON.parse(pako.inflate(zippedData.toString(), { to: 'string' }));
      } catch (err) {
        data = JSON.parse(pako.inflate(zippedData, { to: 'string' }));
      }

      for (let dataPoint of data) {
        switch (dataPoint.source) {
          case 'cloudwatch':
            this.dataPoints.push(new CloudwatchDataPoint(dataPoint));
            break;
          case 'fastly':
            this.dataPoints.push(new FastlyDataPoint(dataPoint));
            break;
          case 'therapist':
            dataPoint.timestamp = checkData.timestamp * 1000;
            this.dataPoints.push(new TherapistDataPoint(dataPoint));
            break;
          default:
            console.log('unimplemented data source' + dataPoint.source);
        }
      }
    } catch (err) {
      console.log(err);
    }
  }
}
