import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';
import { ManageHotelService } from 'src/app/core/services/HotelServices/manage-hotel.service';
import * as moment from 'moment';

@Component({
  selector: 'app-hotel-add-block-date',
  templateUrl: './hotel-add-block-date.component.html',
})
export class HotelAddBlockDateComponent implements OnInit {

  Extranet_Hotel_Id;
  Edit_Id;
  minDate = new Date();
  constructor(public activateRoute:ActivatedRoute,private apiserv: API,public fb:FormBuilder, public validserv:ValidationService,public MsgService:MessageService,    private router: Router,private hotelmanageserv:ManageHotelService) { }
  BlockSearchDaysForm;
  ngOnInit(): void {
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.BlockSearchDaysForm= this.fb.group({
      rule_name:this.validserv.required,
      block_date_type:this.validserv.required,
      extranet_block_date_rule_id:'',
      DateRange:this.fb.array([
        this.fb.group({
          date_from:this.validserv.required,
          date_to:this.validserv.required,
          extranet_block_date_id:'',
        })
      ])
    });
    if(this.Edit_Id){
      this.apiserv.Get('/ExtranetBlockDate/GetExtranetBlockDateById/'+this.Edit_Id).subscribe(res=>{
        if(res && res.status){
          this.setvalue(res.data)
        }
      })
    }
  }
  addDateArr(){
    this.BlockSearchDaysForm.controls['DateRange'].push(
      this.fb.group({
        date_from:this.validserv.required,
        date_to:this.validserv.required,
        extranet_block_date_id:'',
      })
    )
  }
  removeDateArr(i){
    this.BlockSearchDaysForm.controls['DateRange'].removeAt(i)
  }
  setvalue(data){
    this.BlockSearchDaysForm.get('rule_name').setValue(data[0].rule_name);
    this.BlockSearchDaysForm.get('extranet_block_date_rule_id').setValue(data[0].extranet_block_date_rule_id);
    this.BlockSearchDaysForm.get('block_date_type').setValue(data[0].block_date_type);
    data.forEach((date_arr,ind)=>{
      if(ind > 0)this.addDateArr()
      this.BlockSearchDaysForm.controls['DateRange']['controls'][ind].get('extranet_block_date_id').setValue(date_arr.extranet_block_date_id);
    console.log(new Date(date_arr.date_from))
      this.BlockSearchDaysForm.controls['DateRange']['controls'][ind].get('date_from').setValue(new Date(date_arr.date_from));
      this.BlockSearchDaysForm.controls['DateRange']['controls'][ind].get('date_to').setValue(new Date(date_arr.date_to));
    })
  }

  Save(){
    if (this.BlockSearchDaysForm.status == "INVALID") {
      this.validserv.showValidationsMsg(this.BlockSearchDaysForm);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let Req_value = this.BlockSearchDaysForm.getRawValue();
    let ReqObj = []
    Req_value.DateRange.forEach(val=>{
      let from_date = new Date(Date.UTC(val.date_from.getFullYear(), val.date_from.getMonth(), val.date_from.getDate()))
      let to_date = new Date(Date.UTC(val.date_to.getFullYear(), val.date_to.getMonth(), val.date_to.getDate()))
      let Obj={
        extranet_block_date_id:val.extranet_block_date_id,
        extranet_block_date_rule_id:Req_value.extranet_block_date_rule_id ? Req_value.extranet_block_date_rule_id :'',
        extranet_hotel_id:this.Extranet_Hotel_Id ? this.Extranet_Hotel_Id : '',
        rule_name:Req_value.rule_name ? Req_value.rule_name : '',
        block_date_type:Req_value.block_date_type ? Req_value.block_date_type : '',
        date_from:val.date_from ? moment(from_date).toISOString() : '',
        date_to:val.date_to ? moment(to_date).toISOString() : ''
      }
      ReqObj.push(Obj)
    })
    this.apiserv.Post('/ExtranetBlockDate/SaveExtranetBlockDate',ReqObj).subscribe(data=>{
      if(data){
        this.MsgService.add({
          severity: data.status ? "success" : "error",
          detail: data.message,
        });
        data.status ? this.backbutton() : '';
      }
    })
  }

  backbutton(){
    this.hotelmanageserv.Active_tab = 'BlockDates';
    this.router.navigateByUrl("/Services/Hotel/HotelManage/"+this.Extranet_Hotel_Id);
  }

}
