import { Component, OnInit, ViewChild } from "@angular/core";
import { FormBuilder, FormGroup, NgForm, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { BlockUI, NgBlockUI } from "ng-block-ui";
import { BuildingService } from "../../service/monitoring-api.service";

@Component({
  selector: "app-add-edit-device",
  templateUrl: "./add-edit-device.component.html",
  styleUrls: ["./add-edit-device.component.css"],
})
export class AddEditDeviceComponent implements OnInit{
  @ViewChild("f", { read: true }) userProfileForm: NgForm;
  dataMasterCategori: any;
  dataMasterVoltage: any;
  dataMasterType: any;
  dataMasterDuration: any;
  dataMasterStatus: any;
  dataBuildingRoomList: any;
  deviceId: any;

  model: any = {};
  dataDevice: any;
  mode: string;

  @BlockUI("projectInfo") blockUIProjectInfo: NgBlockUI;

  public breadcrumb: any;

  projectInfo: FormGroup;

  submitted = false;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private monitoringApiService: BuildingService,
  ) {}

  ngOnInit() {
    this.route.params.subscribe(params => {
      const id = params['id'];
      this.deviceId = id;
      if (id) {
        this.loadDevice(id);
        this.dataListMaster();
        this.dataListRoomBuilding();
      }
    });
    this.setBreadcrumb()
    this.route.data.subscribe((data) => {
      this.mode = data.mode;
    });

    this.projectInfo = this.formBuilder.group({
      name: ["", Validators.required],
      categoryId: ["", Validators.required],
      voltageId: ["", Validators.required],
      typeId: ["", Validators.required],
      durationId: ["", Validators.required],
      roomBuildingId: ["", Validators.required],
      watt: ["", Validators.required],
    });
  }

  loadDevice(deviceId: string) {
    this.monitoringApiService.getDeviceById(deviceId).subscribe(data => {
      this.dataDevice = data;
      this.formGetDevice(data)
    });
  }

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

      const dataVoltage =  data.data.find(
        (item) => item.name === "master_voltage"
      ).headerDetailParam;
      this.dataMasterVoltage = dataVoltage.filter(item => item.status === "2")

      const dataType = data.data.find(
        (item) => item.name === "master_type"
      ).headerDetailParam;
      this.dataMasterType = dataType.filter(item => item.status === "2")

      const dataDuration = data.data.find(
        (item) => item.name === "master_duration"
      ).headerDetailParam;
      this.dataMasterDuration = dataDuration.filter(item => item.status === "2")

      const dataStatus = data.data.find(
        (item) => item.name === "master_status"
      ).headerDetailParam;
      this.dataMasterStatus = dataStatus.filter(item => item.status === "2")
    });
  }

  dataListRoomBuilding() {
    this.monitoringApiService.getBuildingRoomList().subscribe(data => {
      const newArray = data.results.data.map(item => ({
        id: item.id,
        name: `${item.buildingEntity.name} (${item.roomEntity.name})`
      }));
      this.dataBuildingRoomList = newArray
    });
  }

  formGetDevice(data){
    this.projectInfo.patchValue({
      name: data.data.name,
      categoryId: data.data.categoryId,
      voltageId: data.data.voltageId,
      typeId: data.data.typeId,
      durationId: data.data.durationId,
      roomBuildingId: data.data.roomBuildingId,
      watt: data.data.watt
    });
    if (this.mode === 'view') {
      this.formDisable();
    }
  }

  formDisable(){
    this.projectInfo.get('name').disable()
    this.projectInfo.get('categoryId').disable()
    this.projectInfo.get('voltageId').disable()
    this.projectInfo.get('typeId').disable()
    this.projectInfo.get('durationId').disable()
    this.projectInfo.get('roomBuildingId').disable()
    this.projectInfo.get('watt').disable()
  }

  setBreadcrumb() {
    if (this.isAddMode()) {
      this.breadcrumb = {
        mainlabel: "Device",
        links: [
          {
            name: "Home",
            isLink: false,
          },
          {
            name: "Device",
            isLink: false,
          },
          {
            name: "Add new device",
            isLink: false,
          },
        ],
      };
    } else if (this.isEditMode()) {
      this.breadcrumb = {
        mainlabel: "Device",
        links: [
          {
            name: "Home",
            isLink: false,
          },
          {
            name: "Device",
            isLink: false,
          },
          {
            name: "Edit new device",
            isLink: false,
          },
        ],
      };
    } else if (this.isViewMode()) {
      this.breadcrumb = {
        mainlabel: "Device",
        links: [
          {
            name: "Home",
            isLink: false,
          },
          {
            name: "Device",
            isLink: false,
          },
          {
            name: "View new device",
            isLink: false,
          },
        ],
      };
    }
  }

  isEditMode() {
    return this.mode === "edit";
  }

  isViewMode() {
    return this.mode === "view";
  }

  isAddMode() {
    return this.mode === "add";
  }

  get f() {
    return this.projectInfo.controls;
  }

  onProjectInfoSubmit() {
    this.submitted = true;
    if (this.projectInfo.invalid) {
      return;
    }
  }

  keyPress(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    const inputChar = String.fromCharCode(event.charCode);
    if (event.keyCode !== 8 && !pattern.test(inputChar)) {
      event.preventDefault();
    }
  } 

  saveEdit() {
    this.monitoringApiService.putDevice(this.projectInfo.value, this.deviceId).subscribe(data => {
      this.router.navigate(["/device"]);
    });
  }

  cancel() {
    this.router.navigate(["/device"]);
  }
}
