import { Component, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { FlowRate } from 'src/app/models/flowRate';
import { GrondwaterstandService } from '../grondwaterstand/grondwaterstand.service';
import { DebietService } from './debiet.service';
import { ActivatedRoute } from '@angular/router';
import { ChartData, ChartOptions } from 'chart.js';

@Component({
  selector: 'app-debiet',
  templateUrl: './debiet.component.html',
  styleUrls: ['./debiet.component.css'],
})
export class DebietComponent implements OnInit {
  labels: String[] = [];
  values: number[][] = [];

  salesData: ChartData<'line'> = { datasets: [] };
  chartOptions: ChartOptions = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Monthly Sales Data',
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        max: 25,
      },
    },
  };
  @Input() flowRate: FlowRate = {
    id: 0,
    value: 0,
    timestamp: '',
    wharfID: 0,
  };
  flowrate$: Observable<FlowRate[]> = new Observable<FlowRate[]>();

  constructor(
    private debietService: DebietService,
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    let test: any[];
    this.debietService.getValues().subscribe((result) => {
      console.log('result', result);
      let flowrates: number[] = [];
      let timestamps: string[] = [];
      for (let row in result) {
        // this.labels.push(result[row].id.toString());
        // Hier sorteer ik de array op timestamp
        result.sort((a, b) => {
          const timestamp1 = new Date(a.timestamp);
          const timestamp2 = new Date(b.timestamp);
          return timestamp1.getTime() - timestamp2.getTime();
        });
        flowrates = result.map((res, index) => res.value);
        timestamps = result.map(
          (res, index) =>
            new Date(res.timestamp).toLocaleDateString() +
            ' ' +
            new Date(res.timestamp).toTimeString().substring(0, 5)
        );
      }
      this.salesData = {
        labels: timestamps,
        datasets: [
          {
            label: 'Debiet',
            data: flowrates,
            tension: 0.5,
          },
        ],
      };
    });
    this.flowrate$ = this.debietService.getValues();

    const pumpId = this.route.snapshot.paramMap.get('id');
    const wharfId = this.route.snapshot.paramMap.get('wharIid');
    console.log(wharfId);
  }
}
