import { Component, Input } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap";
import { CostManagementService } from "../../service/cost-management.service";

@Component({
  selector: "app-modal-add-actual",
  templateUrl: "./modal-add-actual.component.html",
  styleUrls: ["./modal-add-actual.component.css"],
})
export class ModalAddActualComponent {
  @Input() buildingId: number;
  @Input() periode: any;

  myForm: FormGroup;
  dateCurrent: any;
  dataCost: any;
  formattedDate: any;
  formattedDate2: any;
  buildingName: any;

  constructor(
    public activeModal: NgbActiveModal,
    private fb: FormBuilder,
    private costService: CostManagementService
  ) {
    this.createForm();
  }

  ngOnInit() {
    const currentDate = new Date();
    this.dateCurrent = currentDate.toISOString().slice(0, 7);
    this.dateFormat();
    this.getBuildingById();
    this.datalistcost();
  }

  dateFormat() {
    let year = this.periode.slice(0, 4);
    let month = this.periode.slice(5, 7);
    let monthNames = [
      "Januari",
      "Februari",
      "Maret",
      "April",
      "Mei",
      "Juni",
      "Juli",
      "Agustus",
      "September",
      "Oktober",
      "November",
      "Desember",
    ];
    let monthName = monthNames[parseInt(month) - 1];
    this.formattedDate = `${monthName} ${year}`;
    this.formattedDate2 = `${year}-${month}`;
    
    
  }

  createForm() {
    this.myForm = this.fb.group({
      real_cost: ["", Validators.required],
    });
  }

  getBuildingById() {
    this.costService.getBUildingById(this.buildingId).subscribe((data) => {
      this.buildingName = data.data.name;
    });
  }

  datalistcost() {
    this.costService
      .getRealCostByBuildingId(this.buildingId, this.formattedDate2)
      .subscribe((data) => {
        this.dataCost = data.data[0];
        this.myForm.patchValue({
          real_cost: data.data[0].real_cost ? data.data[0].real_cost : 0,
        });
      });
  }

  addRow() {
    if (this.myForm.valid) {
      this.costService
        .putRealCost(this.myForm.value, this.dataCost.id)
        .subscribe((data) => {
          console.log(data);

          this.activeModal.close(this.myForm.value);
        });
    }
  }
}
