import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { TableModule } from 'primeng/table';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-hotel-zone-search',
  templateUrl: './hotel-zone-search.component.html',
})
export class HotelZoneSearchComponent implements OnInit {

  hotelZoneSearchForm: FormGroup;

  ddLoader = {
    city: false,
    Country: false,
    hotel_list: false,
  };
  timer;
  HotelList;
  CountryList;
  CityList;
  Result;
  cols;
  constructor(public fb: FormBuilder, private apiserv: API, public commonMasterSer: CommonFunctionService, private router: Router) {

  }

  ngOnInit(): void {
     this.cols = [
      { field: 'zoneName', header: 'Zone Name' },
      { field: 'country', header: 'Country' },
      { field: 'city', header: 'City' },
      { field: "hotels", header: 'Number of Hotel' },
      { field: 'hotelZoneId', header: 'Zone Id' },
      { field: 'status', header: 'Status' },
      { field: 'createdBy', header: 'Created By' },
      { field: 'Custom_created_on', header: 'Created On' },
      { field: 'updatedBy', header: 'Updated By' },
      { field: 'Custom_updated_on', header: 'Updated On' },
    ];
    this.initform();
  }

  initform() {
    this.hotelZoneSearchForm = this.fb.group({
      ZoneName: '',
      HotelName: '',
      Country: '',
      City: '',
    });
  }


  GetHotels(event) {
    if (event.value.length >= 2) {
      let obj = {
        languageCode: 'en',
        cityName: event.value,
        lattitude: '0',
        longitude: '0',
      }
      this.ddLoader['hotel_list'] = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGoPost(`/Hotel/GetHotels`, obj).subscribe(res => {
          if (res) {
            this.HotelList = res.hotels;
            this.ddLoader['hotel_list'] = false;
          }
        });
      }, 500);
    }
  }

  getCountryList(event) {
    if (event.value.length >= 2) {
      this.ddLoader['Country'] = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGet(`/MasterSearch/GetAllCountry/en/${event.value}`).subscribe(res => {
          if (res) {
            this.CountryList = res;
            this.ddLoader['Country'] = false;
          }
        });
      }, 500);
    }
  }

  getHotelCitySearch(event) {
    if (event.value.length >= 2) {
      let reqObj = {
        cityName: event.value,
        languageCode: 'en',
        lattitude: '0',
        longitude: '0'
      }
      this.ddLoader.city = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGoPost("/Hotel/GetHotelCities", reqObj).subscribe(res => {
          if (res) {
            this.CityList = res.cities;
            this.ddLoader.city = false;
          }
        });
      }, 500);
    }
    if (!event.value) {
      this.CityList = [];
    }
  };
  
  Search(){
    let val = this.hotelZoneSearchForm.getRawValue();
    let ReqObj = {
      ZoneName: val.ZoneName ? val.ZoneName : '',
      HotelName: val.HotelName ? val.HotelName : '',
      Country: val.Country ? val.Country : '',
      City: val.City ? val.City : '',
    }
    this.apiserv.Post('/ActivityHotelZone/GetAll', ReqObj).subscribe(res => {
      if (res) {
        this.Result = res.data ? res.data :[];
        if (res.data) {
          this.Result.forEach(e => {
            e['status'] = e.isActive ? 'Active' : 'Deactive';
            e['Custom_updated_on'] = this.commonMasterSer.convertDateWithTimeToShow(e.updatedOn);
            e['Custom_created_on'] = e['createdOn'] ?  this.commonMasterSer.convertDateWithTimeToShow(e.createdOn) : e['createdOn'];
          });
          // customSort(event: SortEvent) {
            this.Result.sort((a: any, b: any) => {
                // Sort by status: Active first, then Deactive
                if (a.status !== b.status) {
                    return a.status === 'Active' ? -1 : 1;
                }
        
                // If both are Active, sort by activeDate
                if (a.status === 'Active') {
                    return new Date(b.updatedOn).getTime() - new Date(a.updatedOn).getTime();
                }
        
                // If both are Deactive, sort by deactiveDate
                return new Date(b.updatedOn).getTime() - new Date(a.updatedOn).getTime();
            });
        // }
        }
      }
    })
  }
  Reset(){
    this.hotelZoneSearchForm.reset();
  }

  Edit(Id){
    this.router.navigateByUrl(`ActivityConfiguration/HotelZone/Edit/${Id}`);
  }
  updateStatus(id, val) {
    let obj = {
      id: id,
      status: val ? false : true,
    };
    this.apiserv.Post('/ActivityHotelZone/UpdateStatus', obj).subscribe(res => {
      if (res) {
        this.commonMasterSer.showMessage(res['status'], res['message']);
        res['status'] ? this.Search() : '';
      }
    });
  }
}
