import { Component, OnInit, Input, ElementRef, Type } from '@angular/core';
/** import { time } from 'echarts';*/
import { Observable, range } from 'rxjs';
import { SensorData } from 'src/app/models/sensorData';
import { Wharf } from 'src/app/models/Wharf';
import { Pump } from 'src/app/models/pump';
import { GrondwaterstandService } from './grondwaterstand.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ChartDataset, ChartData, ChartOptions } from 'chart.js';
import { Chart } from 'chart.js/dist';
@Component({
  selector: 'app-grondwaterstand',
  templateUrl: './grondwaterstand.component.html',
  styleUrls: ['./grondwaterstand.component.css'],
})
export class GrondwaterstandComponent implements OnInit {



  labels_linegraph: String[] = [];
  values_linegraph: number[][] = [];
  labels_bargraph: String[] = [];
  values_bargraph: number[][] = [];
  salesData_linegraph: ChartData<'line'> = { datasets: [] };
  salesData_bargraph: ChartData<'bar'> = { datasets: [] };
  chartOptions_linegraph: ChartOptions = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Verloop grondwaterstand',
      },
    },
  };
  chartOptions_bargraph: ChartOptions = {
    responsive: true,
    backgroundColor: 'lightblue',
    plugins: {
      title: {
        display: true,
        text: 'Momentele grondwaterstand',
      },
    },
  };
  salesData: ChartData<'line'> = { datasets: [] };
  chartOptions: ChartOptions = {};
  wharf$: Observable<Wharf> = new Observable<Wharf>();
  sensordata$: Observable<SensorData[]> = new Observable<SensorData[]>();
  wharfId = this.route.snapshot.paramMap.get('wharIid');

  constructor(
    private grondwaterstandService: GrondwaterstandService,
    private route: ActivatedRoute,
    private elementRef: ElementRef,
    private router: Router
  ) {}

  ngOnInit(): void {

    let wharfdepth = 0;
    this.grondwaterstandService.getWharfById(Number(this.wharfId)).subscribe((wharfres) => {
      wharfdepth = wharfres.wharfDepth;
      console.log(wharfdepth);
      let datas_linegraph: number[] = [];
      this.grondwaterstandService.getSensors().subscribe((result) => {
        console.log('result', result);

        for (let row in result) {
          // Hier sorteer ik de array op timestamp
          result[row].sensorDatas.sort((a, b) => {
            const timestamp1 = new Date(a.timestamp);
            const timestamp2 = new Date(b.timestamp);
            return timestamp1.getTime() - timestamp2.getTime();
          });
          result[row].sensorDatas.map(
            (sensordata, index) =>
              (datas_linegraph[index] = sensordata.waterLevel)
          );
          console.log(datas_linegraph, 'datas');

          let tempdata = JSON.parse(JSON.stringify(datas_linegraph));
          datas_linegraph.length = 0;
          this.values_linegraph[row] = tempdata;
          console.log(this.values_linegraph[0], 'values0');
        }
        let wharfdepths: any = [];
        for (let i = 0 - 5; i < this.values_linegraph[0].length; i++) {
          wharfdepths.push(wharfdepth);
        }
        let data_linegraph: any = [];
        let data_bargraph: any = [];
        this.values_linegraph.map(
          (value, index) => (
            data_linegraph.push({
              label: result[index].gridPos,
              data: value,
              tension: 0.5,
            }),
            this.labels_bargraph.push(result[index].gridPos),
            data_bargraph.push(value[value.length - 1])
          )
        );
        data_linegraph.push({
          label: 'Werf maximum diepte',
          data: wharfdepths,
          tension: 0.5,
          borderColor: 'rgb(0, 0, 0)',
          borderWidth: 2
        });

        const timestamps_linegraph = result[0].sensorDatas.map(
          (sensorData) =>
            new Date(sensorData.timestamp).toLocaleDateString() +
            ' ' +
            new Date(sensorData.timestamp).toTimeString().substring(0, 5)
        );

        console.log('bardata', data_bargraph);
        console.log('lineData', data_linegraph);
        this.salesData_linegraph = {
          labels: timestamps_linegraph,
          datasets: data_linegraph,
        };
        (this.salesData_bargraph = {
          labels: this.labels_bargraph,
          datasets: [
            {

              label: 'Sensoren',
              data: data_bargraph,
              borderSkipped: 'bottom',
              backgroundColor: ['rgba(54, 162, 235, 0.2)',],
              borderColor: [
                'rgb(54, 162, 235)',

              ],
              borderWidth: 2,
              barThickness: 50,
              xAxisID: "TAW",
            },
          ],
        }),
          (this.chartOptions_linegraph = {
            responsive: true,

            scales: {

              y: {
                beginAtZero: true,
                max: 10,
                min: wharfdepth - 1,
                title: {
                  display: true,
                  text: 'TAW',
                },
              },
            },
            plugins: {
              title: {
                display: true,
                text: 'Grondwaterstand (m)',
              },
            },
          });
        this.chartOptions_bargraph = {
          responsive: true,

          scales: {
            y: {
              beginAtZero: true,
              max: 10,
              min: wharfdepth - 1,
              title: {
                display: true,
                text: 'TAW',
              },
            },
          },

          plugins: {
            title: {
              display: true,
              text: 'Grondwaterstand (m)',
            },
          },
        };
      });
    });
  }
}
