import { Component, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { BuildingService } from '../../../service/monitoring-api.service';

@Component({
  selector: 'app-add-edit-master-room',
  templateUrl: './add-edit-master-room.component.html',
  styleUrls: ['./add-edit-master-room.component.css']
})
export class AddEditMasterRoomComponent {
  @Input() dataRow: any;
  @Input() mode: any;
  myForm: FormGroup;

  data: any;
  dataStatus: any[];
  dataBuilding: any[];
  filteredDataStatus: any[];
  filteredDataBuilding: any[];
  dataMasterStatus: any;

  constructor(
    public activeModal: NgbActiveModal,
    private fb: FormBuilder,
    private monitoringApiService: BuildingService
  ) {}

  ngOnInit() {
    this.createForm();
    this.listDataStatus();
    this.listDataBuilding();

    if (this.dataRow) {
      this.editForm();
    }
  }

  createForm() {
    this.myForm = this.fb.group({
      name: ["", Validators.required],
      statusId: [0, Validators.required],
      buildingId: [0, Validators.required],
      description: ["", Validators.required],
    });
  }

  editForm() {
    this.myForm = this.fb.group({
      id: this.dataRow.id,
      name: this.dataRow.name,
      statusId: this.dataRow.statusId,
      buildingId: this.dataRow.buildingId,
      description: this.dataRow.description,
    });
  }

  listDataStatus() {
    this.monitoringApiService.getMasterData().subscribe((res) => {
      this.data = res.results.data;
      this.dataMasterStatus = res.results.data.find(
        (item) => item.name === "master_status"
      );
      this.dataStatus = this.dataMasterStatus.headerDetailParam;
      this.filteredDataStatus = this.dataStatus.filter(
        (item) => item.status === "2"
      );
      
    });
  }

  listDataBuilding(){
    this.monitoringApiService.getMasterBuildingData().subscribe((res) => {
      this.dataBuilding = res.results.data;
      this.filteredDataBuilding = this.dataBuilding.filter(
        (item) => item.statusId === 2
      );
      
    });
  }

  addRow() {
    if (this.myForm.valid) {
      this.activeModal.close(this.myForm.value);
    }
  }
}
