import { Component, ElementRef, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { ChartOptions, ChartType, ChartDataset } from "chart.js";
import { EnergyMonitoringService } from "../../service/energy-monitoring.service";
import { CurrencyPipe } from "@angular/common";

@Component({
  selector: "app-detail",
  templateUrl: "./detail.component.html",
  styleUrls: ["./detail.component.css"],
  providers: [CurrencyPipe],
})
export class DetailComponent {
  data: any;
  mode: string;
  breadcrumb: any;
  donutChart1: any;
  donutChart2: any;

  dataChart = {
    donut: {
      series: [20, 20, 20, 20, 20],
    },
  };

  dataChart2 = {
    donut: {
      series: [50, 50],
    },
  };

  // chart bar
  public barChartOptions: ChartOptions = {
    responsive: true,
    animation: {
      duration: 0 // Menonaktifkan animasi
    },
    scales: {
      x: {
        stacked: true,
      },
      y: {
        stacked: true,
        beginAtZero: true
      },
    },
  };
  
  public barChartLabels: string[] = [];
  public barChartType: ChartType = "bar";
  public barChartLegend = true;
  public barChartData: ChartDataset[] = [
    {
      data: [],
      label: "KWH Consumption",
      backgroundColor: "#C3F164",
      borderColor: "#C3F164",
      pointBackgroundColor: "#C3F164",
      pointBorderColor: "#C3F164",
      pointHoverBackgroundColor: "#ffffff",
      pointHoverBorderColor: "#C3F164",
      barPercentage: 0.5,
      categoryPercentage: 0.5,
    },
    // {
    //   data: [],
    //   label: "Water Consumption",
    //   backgroundColor: "#64CFF1",
    //   borderColor: "#64CFF1",
    //   pointBackgroundColor: "#64CFF1",
    //   pointBorderColor: "#64CFF1",
    //   pointHoverBackgroundColor: "#ffffff",
    //   pointHoverBorderColor: "#64CFF1",
    //   barPercentage: 0.5,
    //   categoryPercentage: 0.5,
    // },
    {
      type: "line",
      data: [],
      label: "Weekly Kwh Average",
      backgroundColor: "rgba(0,255,255,0)",
      borderColor: "#ffffff",
      fill: false,
      pointBorderColor: "#ffffff",
      pointBackgroundColor: "#FFF",
      pointBorderWidth: 2,
      pointHoverBorderWidth: 2,
      pointRadius: 4,
      tension: 0.3,
      spanGaps: true
    },
    // {
    //   type: "line",
    //   data: [],
    //   label: "Weekly Water Average",
    //   backgroundColor: "rgba(0,255,255,0)",
    //   borderColor: "#ffffff",
    //   fill: false,
    //   pointBorderColor: "#ffffff",
    //   pointBackgroundColor: "#FFF",
    //   pointBorderWidth: 2,
    //   pointHoverBorderWidth: 2,
    //   pointRadius: 4,
    //   tension: 0.3,
    //   spanGaps: true
    // },
  ];
  //..........................

  // integrasi
  electric: any;
  water: any;
  device: any;
  room: any;
  topCard: any;
  summaryCost: any;
  airQuality: any;
  temperature: any;
  deviceCategory: any;
  chartKwhWater: any;
  paramsId: any;
  //......

  constructor(
    private route: ActivatedRoute,
    private energyMonitoringService: EnergyMonitoringService,
    private currencyPipe: CurrencyPipe,
    private router: Router,
  ) {}

  get formattedSummaryCost(): string {
    return this.currencyPipe.transform(
      this.summaryCost.summary_cost,
      "IDR",
      "symbol",
      "1.0-0"
    );
  }

  ngOnInit() {
    this.route.data.subscribe((data) => {
      this.mode = data.mode;
    });
    this.breadcrumbLink();
    this.route.params.subscribe((params) => {
      const buildingId = params["id"];
      this.paramsId = params["id"];
      if (buildingId) {
        this.dataEnergyMonitoringTopCard(buildingId);
        this.dataEnergyMonitoringSummary(buildingId);
        this.dataEnergyMonitoringSAir(buildingId);
        this.dataEnergyMonitoringSTemperature(buildingId);
        this.dataEnergyDeviceCategory(buildingId);
        this.dataEnergyChartKwhWater(buildingId);
      }
    });

    this.donutChart1 = {
      type: "Pie",
      data: this.dataChart.donut,
      options: {
        fullwidth: true,
        height: "300px",
        donut: true,
        donutWidth: 70,
        startAngle: 270,
        total: 200,
        showLabel: true,
      },
    };
  }

  breadcrumbLink() {
    this.breadcrumb = {
      mainlabel: "Energy Monitoring",
      linkBack: "/monitoring",
      isLinkBack: true,
      links: [
        {
          name: "Dashboard",
          isLink: false,
          link: "",
        },
        {
          name: "Energy Monitoring",
          isLink: false,
          link: "",
        },
      ],
    };
  }
  //integrasi
  dataEnergyMonitoringTopCard(buildingId) {
    this.energyMonitoringService
      .getDashboardTopCard(buildingId)
      .subscribe((res) => {
        this.topCard = res.data;
      });
  }
  dataEnergyMonitoringSummary(buildingId) {
    this.energyMonitoringService
      .getDashboardSummary(buildingId)
      .subscribe((res) => {
        this.summaryCost = res.data;
      });
  }
  dataEnergyMonitoringSAir(buildingId) {
    this.energyMonitoringService
      .getDashboardAirQuality(buildingId)
      .subscribe((res) => {
        this.airQuality = res.data;
      });
  }
  dataEnergyMonitoringSTemperature(buildingId) {
    this.energyMonitoringService
      .getDashboardTemperature(buildingId)
      .subscribe((res) => {
        this.temperature = res.data;
        this.donutChart2 = {
          type: "Pie",
          data: this.dataChart2.donut,
          options: {
            chartPadding: 0,
            fullwidth: true,
            height: "150px",
            donut: true,
            showLabel: true,
            startAngle: 0,
            labelInterpolationFnc: (value) => {
              const total = this.temperature;
              return total + "°C";
            },
          },
          events: {
            draw: (data: any) => {
              if (data.type === "label") {
                if (data.index === 0) {
                  data.element.attr({
                    dx: data.element.root().width() / 2,
                    dy: data.element.root().height() / 2,
                  });
                } else {
                  data.element.remove();
                }
              }
            },
          },
        };
      });
  }
  dataEnergyDeviceCategory(buildingId) {
    this.energyMonitoringService
      .getDashboardDeviceCategory(buildingId)
      .subscribe((res) => {
        this.deviceCategory = res.data[0];
      });
  }
  dataEnergyChartKwhWater(buildingId) {
    this.energyMonitoringService
      .getDashboardChartKwhWater(buildingId)
      .subscribe((res) => {
        this.chartKwhWater = res.data;
        this.barChartData[0].data = [];
        // this.barChartData[1].data = [];
        this.chartKwhWater.forEach((entry) => {
          this.barChartData[0].data.push(entry.kwh);
          // this.barChartData[1].data.push(entry.water);
          this.barChartLabels.push(entry.day);
        });

        const weeklyKwh = this.aggregateKwhWeekly(this.chartKwhWater);
        // const weeklyWater = this.aggregateWaterWeekly(this.chartKwhWater);

        // Populate Appointment data at every multiple of 7
        let weekIndex = 0;
        for (let i = 0; i < this.barChartData[0].data.length; i++) {
          if (i % 7 === 6 && weekIndex < weeklyKwh.length) {
            this.barChartData[2].data[i] = weeklyKwh[weekIndex++];
          } else {
            this.barChartData[2].data[i] = null;
          }
        }

        // let weekIndexWater = 0;
        // for (let i = 0; i < this.barChartData[0].data.length; i++) {
        //   if (i % 7 === 6 && weekIndexWater < weeklyWater.length) {
        //     this.barChartData[3].data[i] = weeklyWater[weekIndexWater++];
        //   } else {
        //     this.barChartData[3].data[i] = null;
        //   }
        // }
      });
  }
  aggregateKwhWeekly(data: any[]): number[] {
    const weeks = [];
    let weekSum = 0;
    let dayCount = 0;

    data.forEach((entry, index) => {
      weekSum += entry.kwh;
      dayCount++;
      if (dayCount === 7 || index === data.length - 1) {
        weeks.push(weekSum);
        weekSum = 0;
        dayCount = 0;
      }
    });

    return weeks;
  }
  aggregateWaterWeekly(data: any[]): number[] {
    const weeks = [];
    let weekSum = 0;
    let dayCount = 0;

    data.forEach((entry, index) => {
      weekSum += entry.water;
      dayCount++;
      if (dayCount === 7 || index === data.length - 1) {
        weeks.push(weekSum);
        weekSum = 0;
        dayCount = 0;
      }
    });

    return weeks;
  }

  seeMore(paramsId){
    this.router.navigate(["/monitoring/control-device-see-more/", paramsId]);
  }
}
