import { Component, OnInit } from '@angular/core';
import settings from './graph-settings';
import { TokenStorageService } from '../_services/token-storage.service';
import { Socket } from 'ngx-socket-io';
import { map } from 'rxjs/operators';
import { graphset } from 'zingchart-angular/zingchart';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ThrowStmt } from '@angular/compiler';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

//these are the states of the north and south plume controls
/*
states = [  #  status name        open    !open   closed  !closed signal1 signal2
  ('opening requested',  0,       1,      1,       0,      0,      1 ),
  ('opening start',      0,       1,      1,       1,      0,      1 ),
  ('opening',            0,       1,      0,       1,      0,      1 ),
  ('opening',            0,       1,      0,       0,      0,      1 ),
  ('opening end',        1,       1,      0,       0,      0,      1 ),
  ('opening end',        1,       1,      0,       1,      0,      1 ),
  ('open',               1,       0,      0,       1,      0,      1 ),
  ('open',               1,       0,      0,       0,      0,      1 ),   # duplicate
  ('closing requested',  1,       0,      0,       1,      1,      1 ),  #
  ('closing requested',  1,       0,      0,       0,      1,      1 ),  # duplicate
  ('closing start',      0,       0,      0,       1,      1,      1 ),  #  
  ('closing start',      1,       1,      0,       0,      1,      1 ),  # duplicate
  ('closing start',      1,       1,      0,       1,      1,      1 ),  # duplicate
  ('closing',            0,       1,      0,       1,      1,      1 ),
  ('closing end',        0,       1,      1,       1,      1,      1 ),
  ('closed',             0,       1,      0,       0,      1,      1 ),
  ('closed',             0,       1,      1,       0,      1,      1 ),
  ('closed',             1,       1,      1,       0,      1,      1 ),
  ('offline',            0,       0,      0,       0,      0,      0 )
] */

//flume_north IP= 128.193.47.47
//flume_south IP= 128.193.47.46

export class HomeComponent implements OnInit {
  valveInput: number = 0;
  isAdmin = false;
  role = "user";
  g: [zingchart.graphset] = [settings];
  graphvalues;
  constructor(private tokenStorage: TokenStorageService, public socket: Socket, private http: HttpClient) { }

  //controls variables
  // [1hour, 12hour, 1day, 1week, 1 month]
  hourfilter = [1,0,0,0,0];
  //graph config
  config: zingchart.data = {
    gui: {
      "context-menu": {
        empty: true
      }
    },
    graphset: [settings]
  }

  ngOnInit(): void {
    this.socket.emit("msg","hello world");
    //check if the user has admin privileges.
    if(this.tokenStorage.getToken()){
      this.role = this.tokenStorage.getUser().role;
      if(this.role === "admin"){
        this.isAdmin = true;
      }
    }

    //get the data for the graph
    this.http.get("http://35.227.145.19:8080/api/public/graph/data").subscribe(
      data => {
        //got the data
        this.graphvalues = Object.keys(data).map(function(key) {
          return [key, data[key]];
        })

        //sort the data
        this.graphvalues.sort(function(first, second) {
          return second[1][0] - first[1][0];
        })

        this.setgraphdata();
      },
      err => {
        //some error happened
      }
    )
  }
  
 
  onSubmit(): void {
    console.log("valve: " + this.valveInput);
    alert("Setting Water Level to " + this.valveInput);
    //sent this value as command packet to the db eventually getting to the lab server script
    //add authentication verification
  }

  getMessage() {
    return this.socket
        .fromEvent<any>('msg')
        .pipe(map(data => data.msg));
  }

  sendMessage(msg: string) {
    console.log("in homecomponent sending", msg )
    this.socket.emit('msg', msg);
  }

  //get the graph data from the backed, this gets all data.
  getGraphData(){
    
  }

  


  //set the graph data
  setgraphdata() {
    //get the timeframe needed
    let index = this.hourfilter.indexOf(1);
    console.log(index);
    //let date time
    let t = Date.now()

    //get latest time in data
    let time = (this.graphvalues[0][1][0])*0.001;

    let minimumtime = 0;
    let interval = 60;
    switch(index) {
      
      case 0:
        //one hour
        minimumtime = time - 3600;
        break;
      case 1:
        //12 hours
        minimumtime = time - 43200;
        break;
      
      case 2:
        //1 day
        minimumtime = time - 86400;
        break;
      
      case 3:
        //1 week
        minimumtime = time - 604800;
        interval = 3600;
        break;
      
      case 4:
        //1 month
        minimumtime = time - 2628000;
        interval = 86400;
        break;
      default:
    }

    //get a sub 
    var newdata: number[][]=  [];
    var lastadded = 0;
    this.graphvalues.forEach(element => {
      if((element[1][0]*0.001) >= minimumtime && Math.abs(element[1][0]*0.001 - lastadded) >= interval){
        lastadded = (element[1][0]*0.001);
        newdata.push([element[1][0],Number(element[1][1])]);
      }
    });

    console.log(newdata);
    this.g[0].series = [{
      values: newdata,
      'background-color': "#d73f09",
      'line-color': "#d73f09",
      marker: {
          'background-color': "#d73f09",
          'visible': false
      }
    }];
    this.config = {
      gui: {
        "context-menu": {
         empty: true
        }
      },
      graphset: this.g
    } 
  }



  /*
  ** Controls for the graph
  */

  //sets the active filter
  selectTime(time){
    this.hourfilter = [0,0,0,0,0];
    this.hourfilter[time] = 1;
    this.setgraphdata();
  }

  /*
  ** End controls for the graph
  */

  
}