import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';

import { NavController, NavParams, Platform, Content } from 'ionic-angular';

import { Chart } from 'chart.js';

import { SettingBasePage } from '../setting-base/setting-base';

import { MeBaristaService } from '../../providers/me-barista-service';

// import { Gauge } from 'svg-gauge';
import Gauge from 'svg-gauge';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class Home extends SettingBasePage {

  @ViewChild(Content) content: Content; // was allemaal class 'Content'
  @ViewChild('lineCanvas') lineCanvas;
  @ViewChild('powerGauge') powergauge_canvas;
  @ViewChild('timerGauge') shottimer_canvas;
  @ViewChild('spinner') spinner;

  lineChart: any;
  powergauge: any;
  shottimer: any;

  temperature: any;
  target_temperature: any;

  sub_l: any;
  shottimer_show: any;
  shottimer_hide_timeout: any;
  green_gradient: any;


  constructor(public navCtrl: NavController, public navParams: NavParams, public platform: Platform, public cdr: ChangeDetectorRef, public abc: MeBaristaService) {
    super(navCtrl, navParams, cdr, abc);
    this.shottimer_show = false;
  }

  ionViewDidLoad() {
    Chart.defaults.global.legend.display = false;
    Chart.defaults.global.tooltips.enabled = false;

    var line_ctx = this.lineCanvas.nativeElement.getContext('2d')

    let green_gradient = line_ctx.createLinearGradient(0, 0, 0, 150)
    green_gradient.addColorStop(0, 'rgba(46, 204, 113, 0.2)')
    green_gradient.addColorStop(0.4, 'rgba(46, 204, 113, 0.1)')
    green_gradient.addColorStop(1, 'rgba(46, 204, 113, 0)')

    let gray_gradient = line_ctx.createLinearGradient(0, 0, 0, 200)
    gray_gradient.addColorStop(0, 'rgba(240,240,240, 1.0)')
    gray_gradient.addColorStop(0.5, 'rgba(240,240,240, 0.25)')
    gray_gradient.addColorStop(1, 'rgba(240,240,240, 0)')

    this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      animation: true,
      type: 'line',
      options: {
        maintainAspectRatio: false,
        scales: {
          xAxes: [{
            autoSkip: true,
            display: false,
            type: 'time',
            ticks: {
              fontFamily: "Noto Sans"
            }
          }],
          yAxes: [{
            gridLines: {
              drawBorder: false,
              drawOnChartArea: false,
              drawTicks: false
            },
            ticks: {
              fontFamily: '-apple-system, sans-serif',
              mirror: true,
              autoSkip: true,
              callback: function (value, index, values) {
                return value + ' °C';
              }
            }
          }]
        }
      },
      data: {
        labels: this.abc.graph_data['label'],
        datasets: [
          {
            label: "Sensor 1",
            data: this.abc.graph_data['sensor1'],
            fill: false,            
            borderColor: "rgba(144, 12, 63, 0.4)",
            cubicInterpolationMode: "default",
            borderWidth: 2,
            pointRadius: 0,
            lineTension: 1
          },
          {
            label: "Setpoint",
            data: this.abc.graph_data['setpoint'],
            fill: 'origin',
            borderColor: "rgba(46, 204, 113, 0.4)",
            backgroundColor: green_gradient,
            borderWidth: 1,
            pointRadius: 0
          }
        ]
      }

    });

    this.updateData();

    if (this.powergauge == null) {
      this.powergauge = Gauge(this.powergauge_canvas.nativeElement,
        {
          max: 100,
          dialStartAngle: 180,
          dialEndAngle: 0,
          value: 0,
          title: "Power",
          label: function (value) {
            return Math.round(value) + " %";
          }
        });
    }

    

    if (this.shottimer == null) {
      this.shottimer = Gauge(this.shottimer_canvas.nativeElement,
        {
          max: 100,
          dialStartAngle: 180,
          dialEndAngle: 0,
          value: 50,
          title: "Shot",
          label: function (value) {
            return Math.round(value) + " s";
          }

        });
    }

    this.powergauge.setValue(0);
  }

  updateData() {

    //var tmax = Math.max.apply(Math, this.abc.graph_data['sensor1']);
    var tmin = 0 //Math.min.apply(Math, this.abc.graph_data['sensor1']);
    var setpoint = Math.max.apply(Math, this.abc.graph_data['setpoint']);
    

    this.lineChart.options.scales.yAxes[0].ticks.max = Math.round((setpoint + 15) / 5) * 5;
    this.lineChart.options.scales.yAxes[0].ticks.min = tmin; //Math.round((tmin - 15) / 5) * 5;

    var diff = this.abc.graph_data['setpoint'].slice(-1) - this.abc.graph_data['sensor1'].slice(-1);
    let color = { bg: null, border: null }

    if(diff > 20) {
      color.bg = "rgba(144, 12, 63, 0.3)"
      color.border = "rgba(144, 12, 63, 0.75)"
    } else if (diff > 5){
      color.bg = "rgba(255, 195, 0, 0.3)"
      color.border = "rgba(255, 195, 0, 0.75)"
    } else {
      color.bg = "rgba(22, 160, 133, 0.3)"
      color.border = "rgba(22, 160, 133, 0.75)"
    }

    this.lineChart.data.datasets[0].borderColor = color.border
    this.lineChart.options.scales.xAxes[0].time.min = this.abc.graph_data['label'].slice(-200)[0];
    this.lineChart.options.scales.xAxes[0].time.max = this.abc.graph_data['label'].slice(-1)[0];

    this.lineChart.update();

    this.temperature = this.formatTemperature(this.abc.temperature);
    this.target_temperature = this.formatTemperature(setpoint);
    this.spinner_show = !this.abc.connected;
  }

  formatTemperature(temp) {
    return temp.toFixed(1) + ' °C';
  }

  ionViewWillEnter() {
    var f: any;

    //console.log('view-enter');

    // super.ionViewWillEnter( );

    this.sub_l = this.abc.temperature_s1.subscribe(data => {
      //console.log('sub ' + this.abc.temperature); 
      this.powergauge.setValue(this.abc.pid.power);


      // show shot timer when shot has started 
      if (this.abc.shottimer_started)
        this.shottimer_show = true;

      // update timer with current time as long as it running
      // TODO: this does not work for the DEMO

      if (this.abc.shottimer_started) {

        f = new Date();
        this.shottimer.setValue((f - this.abc.shottimer_started) / 1000 * this.abc.speed);

      }

      // when the shot is done, show shot time from meCoffee 
      // and start timer to hide shot timer
      if (this.abc.shottimer_duration) {

        this.shottimer.setValue(this.abc.shottimer_duration / 1000);

        // We have consumed, clear it ( not nice )
        this.abc.shottimer_duration = 0;

        if (this.shottimer_hide_timeout)
          clearTimeout(this.shottimer_hide_timeout);

        this.shottimer_hide_timeout = setTimeout(() => { this.shottimer_show = false; this.shottimer_hide_timeout = null; }, 30 * 1000 / this.abc.speed);

      }

      this.cdr.detectChanges();

      this.updateData();
    });

  }

  ionViewWillLeave() {

    // super.ionViewWillLeave( );

    // this.abc.temperature_s1.unsubscribe();
    this.sub_l.unsubscribe();
  }

  changeOrientation(event: any) {
    //console.log( "changeOrientation " + event );

    // this.content.resize();
    this.ionViewDidLoad(); // fix iOS orientation issues with ChartJS canvas
  }  


  // import { Storage, SqlStorage } from 'ionic-framework/ionic';

  // this.storage = new Storage(SqlStorage);

  // this.storage.get('questionnaires').then((data) => {
  // if (data != null) this.questionnaires = JSON.parse(data);
  // else this.loadDefaultQuestions();
  // And to store Objects, use JSON.stringify(myObject) to store and JSON.parse(...) to turn back

}



