import { Component, ViewChild } from '@angular/core';
import { FormArray, 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-list',
  templateUrl: './add-edit-list.component.html',
  styleUrls: ['./add-edit-list.component.css']
})
export class AddEditListComponent {
  // @ViewChild("f", { read: true }) userProfileForm: NgForm;

  model: any = {};
  mode: string;
  public breadcrumb: any;
  projectInfo: FormGroup;
  submitted = false;

  dataBuildingList: any;
  dataRoomList: any;
  dataMasterStatus: any;
  roombuildingId: any;
  dataRoomBuilding: any;
  // userProfileForm: FormGroup;
  public userList: FormArray;

  @BlockUI("projectInfo") blockUIProjectInfo: NgBlockUI;
  get userFormGroup() {
    return this.projectInfo.get('userArray') as FormArray;
  }

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

  ngOnInit() {
    this.route.data.subscribe((data) => {
      this.mode = data.mode;
    });
    this.route.params.subscribe(params => {
      const id = params['id'];
      this.roombuildingId = id;
      if (id) {
        this.loadRoomBuilding(id);
      }
    });
    this.setBreadcrumb();
    this.dataListBuilding();
    this.dataListRoom();
    this.dataListMaster();

    this.projectInfo = this.formBuilder.group({
      buildingId: ["", Validators.required],
      roomId: [""],
      statusId: ["", Validators.required],
      userArray: this.formBuilder.array([this.createRoom()]),
    });
    this.userList = this.projectInfo.get('userArray') as FormArray;
  }

  createRoom(): FormGroup {
    return this.formBuilder.group({
      roomId: ['', Validators.required]
    });
  }

  addPhone() {
    this.userList.push(this.createRoom());
  }

  removePhone(index) {
    this.userList.removeAt(index);
  }

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

  loadRoomBuilding(deviceId: string) {
    this.monitoringApiService.getRoomBuildingById(deviceId).subscribe(data => {
      this.dataRoomBuilding = data;
      this.formGetDevice(data)
    });
  }

  formGetDevice(data){
    this.projectInfo.patchValue({
      buildingId: data.data.buildingId,
      roomId: data.data.roomId,
      statusId: data.data.statusId,
    });
    
    if (this.mode === 'view') {
      this.formDisable();
    }
  }

  formDisable(){
    this.projectInfo.get('buildingId').disable()
    this.projectInfo.get('roomId').disable()
    this.projectInfo.get('statusId').disable()
  }

  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();
    }
  }

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

  dataListRoom() {
    this.monitoringApiService.getListRoomData().subscribe(data => {
      this.dataRoomList = data.data
    });
  }

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

  save() {
    if (this.mode === 'add') {
      if (this.projectInfo.invalid) {
        return;
      }
      const formData = this.projectInfo.value;
      const transformedData = {
        buildingId: formData.buildingId,
        roomId: formData.userArray.map(room => room.roomId),
        statusId: formData.statusId
      };
      this.monitoringApiService.postBatchBuilding(transformedData).subscribe((res) => {
        this.router.navigate(["/list-monitoring"]);
      });
    } else {
      delete this.projectInfo.value.userArray;
      this.monitoringApiService.puttBuildingRoom(this.projectInfo.value, this.roombuildingId).subscribe(data => {
        this.router.navigate(["/list-monitoring"]);
      });
    }
  }

  cancel() {
    this.router.navigate(["/list-monitoring"]);
  }
}
