import { Component, ElementRef, ViewChild } from "@angular/core";
import { Router } from "@angular/router";
import { DeviceService } from "../../service/device.service";
import { BuildingService } from "../../service/monitoring-api.service";
import videojs from "video.js";

@Component({
  selector: "app-surveillance",
  templateUrl: "./surveillance.component.html",
  styleUrls: ["./surveillance.component.css"],
})
export class SurveillanceComponent {
  @ViewChild("videoIframe", { static: false }) videoIframe: ElementRef;

  filteredRows: any[];
  searchTerm: string = "";
  buildingSelected: any;
  statusSelected: any;
  categorySelected: any;
  dataMasterCategori: any;
  dataBuildingList: any;
  dataMasterStatus: any;
  storedData: any;
  spinnerFilterActive = false;
  switchState: boolean;
  public breadcrumb: any;
  showIframe = false;
  clicktrue = false;

  bufferingTimeout: any;

  cameras = [
    {
      id: 1,
      name: "Pengadilan Agama Padang Cam 1",
      videoUrl:
        "https://wework-1-us.stream.iot-11.com:8080/hls/eb48441e886701e55bbk52/cpsgbti59barred964v0pXFm2hujw6pfrksNebnJ.m3u8?signInfo=1nOzF8oTGaesUDaWKWwVvm48YUWzA1giepIfLDeyEYHizShw3V4xT0zp9YI7NBbpOiPBfg1zDalVkjzpVQL_6l9z6Q3TptY5lOW3FkZFb7U3lbqHzHiLCh89GKPH6DvUzYXymA4X2hsKU89jJ9y9UwVZwUxs0jHq19rk3CrZ0cE",
    },
    {
      id: 2,
      name: "Pengadilan Agama Padang Cam 2",
      videoUrl:
        "https://wework-4-us.stream.iot-11.com:8080/hls/eb48441e886701e55bbk52/cpsgq28n0asmj2buiihgh0ssY0CuqMVC9LCVeEQH.m3u8?signInfo=0j00FMq5E3kn3oIImQU1laHoYvbLKZuQ8f_IPgKZjRPysw_xbZGfXpbqqP05DnRlsyG40oPuYr2dSylrSppO4vkr0YtJqeTTy0FELIv4nrLAv2vcMyD6So4NJev-nmHpS3GPOIuTiy879xuADEtnYMIt5BqU68L3s9yKaJx5AAE",
    },
    {
      id: 3,
      name: "Pengadilan Agama Purwakarta Cam 1",
      videoUrl:
        "https://bdg2.cctvbadilag.my.id:5443/400854PAPURWAKARTA/play.html?name=194533247298993755522217",
    },
    {
      id: 4,
      name: "Pengadilan Agama Purwakarta Cam 2",
      videoUrl:
        "https://bdg2.cctvbadilag.my.id:5443/400854PAPURWAKARTA/play.html?name=113658520181242556385273",
    },
  ];
  private intervalId: any;
  player: any;
  constructor(
    private router: Router,
    private deviceService: DeviceService,
    private monitoringApiService: BuildingService
  ) {}

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Surveillance",
      links: [
        {
          name: "Home",
          isLink: false,
          link: "",
        },
        {
          name: "Surveillance",
          isLink: false,
        },
      ],
    };
    this.storedData = JSON.parse(localStorage.getItem("currentUser"));
    this.buildingSelected = this.storedData.buildingId;
    this.fetchData(
      this.buildingSelected,
      this.categorySelected,
      this.statusSelected
    );
    this.dataListMaster();
    this.dataListBuilding();
  }

  ngAfterViewInit() {
    const deviceid = localStorage.getItem("deviceId");
    const parsedData = JSON.parse(deviceid);
    console.log(parsedData, "parsedData");

    this.deviceService
      .getStreamUrl(parsedData.device_id)
      .subscribe((data) => {
        console.log("hit ini");

        const options = {
          controls: true,
          autoplay: true,
          preload: "none",
          techOrder: ["html5"],
          html5: {
            hls: {
              overrideNative: !videojs.browser.IS_SAFARI,
            },
          },
        };
        this.player = videojs("streamplayer", options);
        this.player.src({
          type: "application/x-mpegURL",
          src: data.result.data.result.url,
        });

        // Event listener for errors
        this.player.on("error", () => {
          const error = this.player.error();
          console.error("Video error:", error);
          // Handle the error
        });

        // Event listener for stalled
        this.player.on("stalled", () => {
          console.warn("Video playback stalled");
          // Handle the stall
        });

        this.player.on("waiting", () => {
          console.warn("Video playback buffer");
          this.clearBufferingTimeout();
          this.bufferingTimeout = setTimeout(() => {
            const savedData = localStorage.getItem("deviceId");
            const parsedData = JSON.parse(savedData);
            console.log('masuk timeout buffer');
            this.loadStream(parsedData.device_id);
          }, 60000);
        });
        this.player.on("playing", () => {
          this.clearBufferingTimeout();
        });
      });
  }

  loadStream(device_id) {
    localStorage.setItem("deviceId", JSON.stringify({ device_id: device_id }));
    this.deviceService.getStreamUrl(device_id).subscribe((data) => {
      this.player.src({
        type: "application/x-mpegURL",
        src: data.result.data.result.url,
      });
      this.player.controls(true);
      this.player.play();
    });
  }

  clearBufferingTimeout() {
    if (this.bufferingTimeout) {
      clearTimeout(this.bufferingTimeout);
      this.bufferingTimeout = null;
    }
  }

  fetchData(buildingSelected, categorySelected, statusSelected) {
    this.deviceService
      .getDeviceData(buildingSelected, categorySelected, statusSelected)
      .subscribe((res) => {
        this.filteredRows = res.results.data.filter(
          (item) => item.category_id === 30
        );
        localStorage.setItem(
          "deviceId",
          JSON.stringify({ device_id: this.filteredRows[0].device_id })
        );
        this.deviceService
          .getStreamUrl(this.filteredRows[0].device_id)
          .subscribe((data) => {
            const options = {
              controls: true,
              autoplay: true,
              preload: "none",
              techOrder: ["html5"],
              html5: {
                hls: {
                  overrideNative: !videojs.browser.IS_SAFARI,
                },
              },
            };
            this.player = videojs("streamplayer", options);
            this.player.src({
              type: "application/x-mpegURL",
              src: data.result.data.result.url,
            });
          });
        console.log(this.filteredRows, "filteredrow");
      });
  }

  dataListMaster() {
    this.monitoringApiService.getMasterListData().subscribe((data) => {
      const dataCategory = data.data.find(
        (item) => item.name === "master_category"
      ).headerDetailParam;
      const dataStatus = data.data.find(
        (item) => item.name === "master_status"
      ).headerDetailParam;
      this.dataMasterCategori = dataCategory.filter(
        (item) => item.status === "2"
      );
      this.dataMasterStatus = dataStatus.filter((item) => item.status === "2");
    });
  }

  dataListBuilding() {
    this.monitoringApiService.getBuildingList().subscribe((data) => {
      this.dataBuildingList = data.data.filter((item) => item.statusId === 2);
    });
  }

  dataListDevice() {
    this.monitoringApiService.getBuildingList().subscribe((data) => {
      this.dataBuildingList = data.data.filter((item) => item.statusId === 2);
    });
  }

  doFilter() {
    this.spinnerFilterActive = true;
    this.fetchData(
      this.buildingSelected,
      this.categorySelected,
      this.statusSelected
    );
    setTimeout(() => {
      this.spinnerFilterActive = false;
    }, 3000);
  }

  ngOnDestroy() {
    localStorage.removeItem("deviceId");
    this.clearBufferingTimeout();
    if (this.player) {
      this.player.dispose();
    }
  }

  // onClick(videoUrl: string) {
  //   const iframe = this.videoIframe.nativeElement;
  //   iframe.src = videoUrl;
  //   this.clicktrue = true;
  // }

  // onMouseEnter(camera: any) {
  //   if (this.clicktrue === false) {
  //     const iframe = this.videoIframe.nativeElement;
  //     iframe.src = camera.videoUrl;
  //   }
  //   this.showIframe = true;
  // }

  // onMouseLeave() {
  //   const iframe = this.videoIframe.nativeElement;
  //   if (this.clicktrue === false) {
  //     iframe.src = "";
  //   }
  //   this.showIframe = false;
  // }
}
