import { Component, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Route, Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { FlightDetailobj, UpdateFlightDetail } from 'src/app/core/models/flight-service/flight-service-manage/edit-flight-details.model';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-edit-flight-details',
  templateUrl: './edit-flight-details.component.html',
})
export class EditFlightDetailsComponent implements OnInit {

  constructor(public router: ActivatedRoute,
    private ApiServ: API,
    public Fb: FormBuilder, public CommonVar: StaticDataService,
    public validationService: ValidationService,
    public MsgService: MessageService, public route: Router
  ) { }
  contract_id;
  Formdata: FormGroup;
  SearchForm: FormGroup;
  is_search = false;
  is_round_trip = false;
  AirportListFrom;
  AirportListTO;
  lovKeyDataObj = {
    DaySelect: [],
  };
  AirlineList;
  datelist;
  AllAircraftTypeList
  @ViewChild('calender') calender




  ngOnInit(): void {
    this.GetAllAircraftType();
    this.checkIsRangetype();
    this.OnIntForm();
    this.GetLOVKeys('DaySelect');
  }

  checkDateForHighlight(date) {
    let month = date.month > 9 ? date.month : '0' + date.month;
    let d = new Date(date.year, date.month, date.day);
    let new_Date = month + '-' + date.day + '-' + date.year;
    let Checkformat = moment(new_Date).format('MM-DD-YYYY')
    let validate;
    validate = false;
    if (new_Date == Checkformat) {
      let format = moment(d).format('MM-DD-YYYY')
      let valid = this.datelist.filter(e => e == format)
      if (valid.length > 0) {
        validate = true;
      }
    }
    return validate
  }

  checkIsRangetype() {
    this.router.queryParams.subscribe(obj => {
      this.contract_id = obj['id']
      this.ApiServ.Get('/FlightContract/GetFlightDates?ContractId=' + this.contract_id).subscribe(data => {
        if (data) {
          this.GetFlightDetails();
          if (data.responseObject.is_multi_day && !data.responseObject.is_round_trip) {
            this.SetTimeAvali(data.responseObject.dates);
            this.is_search = false;
            this.setFilterValid(true);
          } else {
            this.is_search = true;
            this.AddFLightRoundArr();
            this.Formdata.removeControl('date')
            this.Formdata.removeControl('days')
          }
          if (data.responseObject.is_round_trip) {
            this.is_round_trip = true;
          }

        }
      });
    })
  }
  formDate;
  SetTimeAvali(allDate) {
    this.datelist = allDate.split(',');
    let obj = [];
    this.datelist.map(e => {
      obj.push(moment(e).format('MM-DD-YYYY'));
    })
    this.datelist = obj;
  }
  // 
  DateRangecheck() {
    let date_range = this.Formdata.get('date').value
    if (date_range[1]) {
      this.calender.overlayVisible = false;
      let AllSelectDate = []
      this.datelist.filter(e => {
        let from = moment(date_range[0]).format('MM:DD:YYYY').split(':')
        let To = moment(date_range[1]).format('DD:MMM:YYYY').split(':')
        let maindate = moment(e).format('DD:MMM:YYYY').split(':')
        if (from[1] == maindate[1] || To[1] == maindate[1]) {
          let date = new Date(e).getDate();
          let St = new Date(date_range[0]).getDate();
          let et = new Date(date_range[1]).getDate();
          (date >= St && date <= et) ? AllSelectDate.push(e) : ''
        }
      })
      this.formDate = AllSelectDate;
      console.log(AllSelectDate)
    }
  }

  GetFlightDetails() {
    this.ApiServ.Get('/FlightContract/GetFlightDetails?ContractId=' + this.contract_id).subscribe(data => {
      if (data) {
        this.SetValForm(data.responseObject)
      }
    });
  }


  GetLOVKeys(lov_key_names) {
    let lov_key_names_arr = lov_key_names.split(',');
    let lov_obj = {
      "lov_types": [],
      "lov_lang": "en"
    };
    lov_key_names_arr.forEach(key_name => {
      lov_obj.lov_types.push({ "lov_type": key_name });
    });
    this.ApiServ.Post('/LovMaster/GetLov', lov_obj).subscribe(lov_data => {
      if (lov_data && lov_data.status) {
        lov_key_names_arr.forEach(key_name => {
          let arr = lov_data.responseObject.filter(el => el.lov_type == key_name);
          arr.length > 0 ? this.lovKeyDataObj[key_name] = arr[0].keys : '';
        });
      }
    });
  };

  OnIntForm() {
    this.Formdata = this.Fb.group({
      date: this.validationService.required,
      days: this.validationService.required,
      FlightDetail: this.Fb.array([
        this.Fb.group({
          airline_code: this.validationService.required,
          flight_no: this.validationService.required,
          _aircraft_type: this.validationService.required,
          from_airport: [{ value: '', disabled: true }, Validators.required],
          to_airport: [{ value: '', disabled: true }, Validators.required],
          departure_Hour: this.validationService.required,
          departure_minutes: this.validationService.required,
          departure_terminal: this.validationService.required,
          is_next_day_arrival: [false],
          sector_nbr: [],
          arrival_hour: this.validationService.required,
          arrival_minutes: this.validationService.required,
          arrival_terminal: this.validationService.required,
          flying_duration_hour: this.validationService.required,
          flying_duration_minutes: this.validationService.required,
          is_next_day_departure: [false],
        })
      ])

    });
  }

  get FlightDetail() {
    return this.Formdata.get('FlightDetail') as FormArray;
  }
  get Return_flight() {
    return this.Formdata.get('Return_flight') as FormArray;
  }



  // all hit  


  GetAllAirline(val) {
    if (val) {
      this.ApiServ.Get('/MasterSearch/GetAllAirline/en/' + val).subscribe(obj => {
        if (obj) {
          this.AirlineList = obj;
        }
      });
    }
  }

  GetAllAircraftType() {
    this.ApiServ.Get('/MasterSearch/GetAllAircraftType').subscribe(obj => {
      if (obj) {
        this.AllAircraftTypeList = obj;
      }
    });
  }

  getAirportDetails(val, check) {
    if (val.length >= 3) {
      this.ApiServ.Get('/MasterSearch/GetAllMasterSearch/en/' + val).subscribe(obj => {
        if (obj) {
          if (check) this.AirportListFrom = obj;
          if (!check) this.AirportListTO = obj;
        }
      });
    }
  }

  addFlightGroupBtn(FormName) {
    let formgroup
    FormName == 'FlightDetail' ? formgroup = this.FlightDetail : formgroup = this.Return_flight
    formgroup.push(
      this.Fb.group({
        airline_code: this.validationService.required,
        flight_no: this.validationService.required,
        _aircraft_type: this.validationService.required,
        from_airport: [{ value: '', disabled: true }, Validators.required],
        to_airport: [{ value: '', disabled: true }, Validators.required],
        departure_Hour: this.validationService.required,
        departure_minutes: this.validationService.required,
        departure_terminal: this.validationService.required,
        is_next_day_arrival: [false],
        sector_nbr: [''],
        arrival_hour: this.validationService.required,
        arrival_minutes: this.validationService.required,
        arrival_terminal: this.validationService.required,
        flying_duration_hour: this.validationService.required,
        flying_duration_minutes: this.validationService.required,
        is_next_day_departure: [false],
      })
    )
  };
  removeFlightGroupBtn(ind, formname) {
    let formgroup
    formname == 'FlightDetail' ? formgroup = this.FlightDetail : formgroup = this.Return_flight
    formgroup.removeAt(ind);
  };
  Saveflightdetails() {
    if (this.Formdata.status == "INVALID") {
      this.validationService.showValidationsMsg(this.Formdata);
      return;
    }
    let value = this.Formdata.getRawValue();
    let OutbondList = this.FlightDetail.getRawValue()
    let returnList = this.Return_flight ? this.Return_flight.getRawValue() : []
    let date = moment(new Date).format('YYYY-MM-DD');
    let AllFlightDetailslist = [];
    OutbondList.map((e, i) => {
      let fligtDetlPostData = new FlightDetailobj();
      fligtDetlPostData.airline_code = e.airline_code
      fligtDetlPostData.flight_no = e.flight_no;
      // fligtDetlPostData._aircraft_type = e._aircraft_type;
      fligtDetlPostData.from_airport = e.from_airport;
      fligtDetlPostData.to_airport = e.to_airport;
      fligtDetlPostData.departure_time = date + 'T' + e.departure_Hour + ':' + e.departure_minutes + ':00';
      fligtDetlPostData.is_next_day_departure = e.is_next_day_departure;
      fligtDetlPostData.departure_terminal = e.departure_terminal;
      fligtDetlPostData.is_next_day_arrival = e.is_next_day_arrival;
      fligtDetlPostData.arrival_time = date + 'T' + e.arrival_hour + ':' + e.arrival_minutes + ':00';
      fligtDetlPostData.arrival_terminal = e.arrival_terminal;
      fligtDetlPostData.flying_duration = date + 'T' + e.flying_duration_hour + ':' + e.flying_duration_minutes + ':00';
      fligtDetlPostData._sector_type = '1';
      fligtDetlPostData.sector_nbr = e.sector_nbr;
      fligtDetlPostData.leg_nbr = i + 1;
      AllFlightDetailslist.push(fligtDetlPostData);
    });

    this.is_search ? returnList.map((e, i) => {
      let fligtDetlPostData = new FlightDetailobj();
      fligtDetlPostData.airline_code = e.airline_code
      fligtDetlPostData.flight_no = e.flight_no;
      // fligtDetlPostData._aircraft_type = e._aircraft_type;
      fligtDetlPostData.from_airport = e.from_airport;
      fligtDetlPostData.to_airport = e.to_airport;
      fligtDetlPostData.departure_time = date + 'T' + e.departure_Hour + ':' + e.departure_minutes + ':00';
      fligtDetlPostData.is_next_day_departure = e.is_next_day_departure;
      fligtDetlPostData.departure_terminal = e.departure_terminal;
      fligtDetlPostData.is_next_day_arrival = e.is_next_day_arrival;
      fligtDetlPostData.arrival_time = date + 'T' + e.arrival_hour + ':' + e.arrival_minutes + ':00';
      fligtDetlPostData.arrival_terminal = e.arrival_terminal;
      fligtDetlPostData.flying_duration = date + 'T' + e.flying_duration_hour + ':' + e.flying_duration_minutes + ':00';
      fligtDetlPostData._sector_type = '2';
      fligtDetlPostData.sector_nbr = e.sector_nbr;
      fligtDetlPostData.leg_nbr = i + 1;
      AllFlightDetailslist.push(fligtDetlPostData);
    }) : '';

    let postdata = new UpdateFlightDetail();
    postdata.contract_id = this.contract_id;
    postdata.departure_dates = this.is_search ? '' : this.formDate.join(',');
    postdata.flight_detail = AllFlightDetailslist;
    postdata.outbound_days = this.is_search ? '' : value.days.join(',');
    this.ApiServ.Post('/FlightContract/UpdateFlightDetails', postdata).subscribe(data => {
      if (data) {
        this.MsgService.add({
          severity: data["status"] ? "success" : "error",
          detail: data["message"],
        });
        data["status"] ? setTimeout(() => {
          this.route.navigate(['/Services/FlightServices/Search'])
        }, 500) : '';
      }
    });


  };
  SetValForm(Obj) {
    let departure = Obj.filter(e => e._sector_type == '1')
    let Round = Obj.filter(e => e._sector_type == '2')
    let departure_arr = departure.sort((a, b) => a.leg_nbr - b.leg_nbr)
    let round_arr = Round.sort((a, b) => a.leg_nbr - b.leg_nbr)
    departure_arr ? departure_arr.map((list_obj, i) => {
      i == 0 ? '' : this.addFlightGroupBtn('FlightDetail')
      Object.keys(list_obj).forEach(d => {
        if (d == 'arrival_hour') {
          this.FlightDetail.controls[i].get(d).setValue(list_obj[d])
        } else if (d == 'sector_nbr') {
          this.FlightDetail.controls[i].get('sector_nbr').setValue(list_obj[d])
        } else if (d == 'airline_code') {
          this.GetAllAirline(list_obj[d])
          this.FlightDetail.controls[i].get(d).setValue(list_obj[d])
        } else if (d == 'flight_no' || d == '_aircraft_type' || d == 'arrival_terminal' ||
          d == 'departure_terminal' || d == 'is_next_day_arrival' || d == 'is_next_day_departure') {
          this.FlightDetail.controls[i].get(d).setValue(list_obj[d])

        } else if (d == 'from_airport' || d == 'to_airport') {
          d == 'from_airport' ? this.getAirportDetails(list_obj[d], true) : this.getAirportDetails(list_obj[d], false)
          this.FlightDetail.controls[i].get(d).setValue(list_obj[d])
        } else if (d == 'departure_time') {
          let hour = moment(list_obj[d]).format('h:mm').split(':')[0]
          let minutes = moment(list_obj[d]).format('h:mm').split(':')[1]
          this.FlightDetail.controls[i].get('departure_Hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.FlightDetail.controls[i].get('departure_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)

        } else if (d == 'arrival_time') {
          let hour = moment(list_obj[d]).format('h:mm').split(':')[0]
          let minutes = moment(list_obj[d]).format('h:mm').split(':')[1]
          this.FlightDetail.controls[i].get('arrival_hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.FlightDetail.controls[i].get('arrival_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        } else if (d == 'flying_duration') {
          let hour = moment(list_obj[d]).format('h:mm').split(':')[0]
          let minutes = moment(list_obj[d]).format('h:mm').split(':')[1]
          this.FlightDetail.controls[i].get('flying_duration_hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.FlightDetail.controls[i].get('flying_duration_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        }
      });
    }) : '';

    round_arr ? round_arr.map((list_obj, i) => {
      i == 0 ? '' : this.addFlightGroupBtn('Return_flight')
      Object.keys(list_obj).forEach(d => {
        if (d == 'arrival_hour') {
          this.Return_flight.controls[i].get(d).setValue(list_obj[d])
        } else if (d == 'sector_nbr') {
          this.Return_flight.controls[i].get('sector_nbr').setValue(list_obj[d])
        }
        else if (d == 'airline_code') {
          this.GetAllAirline(list_obj[d])
          this.Return_flight.controls[i].get(d).setValue(list_obj[d])
        } else if (d == 'flight_no' || d == '_aircraft_type' || d == 'arrival_terminal' ||
          d == 'departure_terminal' || d == 'is_next_day_arrival' || d == 'is_next_day_departure') {
          this.Return_flight.controls[i].get(d).setValue(list_obj[d])

        } else if (d == 'from_airport' || d == 'to_airport') {
          d == 'from_airport' ? this.getAirportDetails(list_obj[d], true) : this.getAirportDetails(list_obj[d], false)
          this.Return_flight.controls[i].get(d).setValue(list_obj[d])
        } else if (d == 'departure_time') {
          let hour = moment(list_obj[d]).format('h:mm').split(':')[0]
          let minutes = moment(list_obj[d]).format('h:mm').split(':')[1]
          this.Return_flight.controls[i].get('departure_Hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.Return_flight.controls[i].get('departure_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)

        } else if (d == 'arrival_time') {
          let hour = moment(list_obj[d]).format('h:mm').split(':')[0]
          let minutes = moment(list_obj[d]).format('h:mm').split(':')[1]
          this.Return_flight.controls[i].get('arrival_hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.Return_flight.controls[i].get('arrival_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        } else if (d == 'flying_duration') {
          let hour = moment(list_obj[d]).format('h:mm').split(':')[0]
          let minutes = moment(list_obj[d]).format('h:mm').split(':')[1]
          this.Return_flight.controls[i].get('flying_duration_hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.Return_flight.controls[i].get('flying_duration_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        }
      });
    }) : '';


  };

  ///  validation  form
  setFilterValid(check) {
    if (check) {
      this.addvalid('date', 'add');
      this.addvalid('days', 'add');
    } else {
      this.addvalid('date', 'remove');
      this.addvalid('days', 'remove');
    }
  };

  addvalid(name, type) {
    if (type == 'add') {
      this.Formdata.controls[name].addValidators([Validators.required]);
      this.Formdata.controls[name].updateValueAndValidity();
    } else {
      this.Formdata.controls[name].clearValidators();
      this.Formdata.controls[name].updateValueAndValidity();
      this.Formdata.controls[name].markAsUntouched();
    }
  };

  // validation 
  // nextdayarrivelcheck(check, ind, formname) {
  //   if (check) {
  //     this.AddOutboundtvalid(ind, 'arrival_hour', 'add', formname);
  //     this.AddOutboundtvalid(ind, 'arrival_minutes', 'add', formname);
  //     this.AddOutboundtvalid(ind, 'arrival_terminal', 'add', formname);
  //     this.AddOutboundtvalid(ind, 'flying_duration_hour', 'add', formname);
  //     this.AddOutboundtvalid(ind, 'flying_duration_minutes', 'add', formname);
  //   } else {
  //     this.AddOutboundtvalid(ind, 'arrival_hour', 'remove', formname);
  //     this.AddOutboundtvalid(ind, 'arrival_minutes', 'remove', formname);
  //     this.AddOutboundtvalid(ind, 'arrival_terminal', 'remove', formname);
  //     this.AddOutboundtvalid(ind, 'flying_duration_hour', 'remove', formname);
  //     this.AddOutboundtvalid(ind, 'flying_duration_minutes', 'remove', formname);
  //   }

  // }

  AddOutboundtvalid(index, name, type, formname) {
    let formgroup;
    formname == 'FlightDetail' ? formgroup = this.FlightDetail : formgroup = this.Return_flight
    if (type == 'add') {
      formgroup.controls[index].get(name).addValidators([Validators.required]);
      formgroup.controls[index].get(name).updateValueAndValidity();
    } else {
      formgroup.controls[index].get(name).clearValidators();
      formgroup.controls[index].get(name).updateValueAndValidity();
      formgroup.controls[index].get(name).markAsUntouched();
    }
  };


  AddFLightRoundArr() {
    this.Formdata.addControl(
      'Return_flight', this.Fb.array([
        this.Fb.group({
          airline_code: this.validationService.required,
          flight_no: this.validationService.required,
          _aircraft_type: this.validationService.required,
          from_airport: [{ value: '', disabled: true }, Validators.required],
          to_airport: [{ value: '', disabled: true }, Validators.required],
          departure_Hour: this.validationService.required,
          departure_minutes: this.validationService.required,
          departure_terminal: this.validationService.required,
          is_next_day_arrival: [false],
          sector_nbr: [''],
          arrival_hour: this.validationService.required,
          arrival_minutes: this.validationService.required,
          arrival_terminal: this.validationService.required,
          flying_duration_hour: this.validationService.required,
          flying_duration_minutes: this.validationService.required,
          is_next_day_departure: [false],
        })
      ])
    );
  };










































  rangeDates: Date[];
  cities = [
    { id: 1, name: 'Oneway' },
    { id: 2, name: 'Roundtrip' },
  ];
  AirlineCode = [
    { id: 0, name: 'Select' },
    { id: 1, name: 'EK' },
  ];
  selectAirlineCode = this.AirlineCode[0].name;

  AircraftType = [
    { id: 0, name: 'Select' },
    { id: 1, name: 'a' },
    { id: 1, name: 'b' },
    { id: 1, name: 'c' },
  ];
  selectAircraftType = this.AircraftType[0].name;
  date1: Date;
  date2: Date;
  date3: Date;
  date4: Date;
  // rangeDates: Date[];
  selectedCity = this.cities[0].name;




}
