import { Component, OnInit } from "@angular/core";
import { FormArray, FormBuilder, FormGroup, 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-new-building-room",
  templateUrl: "./add-new-building-room.component.html",
  styleUrls: ["./add-new-building-room.component.css"],
})
export class AddNewBuildingRoomComponent implements OnInit {
  public breadcrumb: any;
  dataMasterstatus: any;
  listRoomMaster: any;
  listBuildingMaster: any;
  mode: string;
  userProfileForm: FormGroup;
  public userList: FormArray;
  submitted = false;
  get userFormGroup() {
    return this.userProfileForm.get('userArray') as FormArray;
  }

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

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Add building",
      links: [
        {
          name: "Add Building",
          isLink: false,
        },
      ],
    };
    this.userProfileForm = this.formBuilder.group({
      buildingId: ['', Validators.required],
      roomId: [''],
      statusId: ['', Validators.required],
      userArray: this.formBuilder.array([this.createRoom()]),
    });

    this.userList = this.userProfileForm.get('userArray') as FormArray;
    this.listMaster();
    this.listRoom();
    this.listBuilding();
  }

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

  listMaster() {
    this.monitoringApiService.getMasterData().subscribe((res) => {
      this.dataMasterstatus = res.results.data.find(
        (item) => item.name === "master_status"
      ).headerDetailParam;
      
    });
  }

  listRoom() {
    this.monitoringApiService.getListRoomData().subscribe((res) => {
      this.listRoomMaster = res.results;
    });
  }

  listBuilding(){
    this.monitoringApiService.getMasterBuildingData().subscribe((res) => {
      this.listBuildingMaster = res.results.data;
      console.log(this.listBuildingMaster);
      
    });
  }

  save(){
    this.submitted = true;

    if (this.userProfileForm.invalid) {
      return;
    }

    const formData = this.userProfileForm.value;
    const transformedData = {
      buildingId: formData.buildingId,
      roomId: formData.userArray.map(room => room.roomId),
      statusId: formData.statusId
    };

    this.monitoringApiService.postBatchBuilding(transformedData).subscribe((res) => {
      console.log(res);
    });
    
  }

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

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

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