import { Injectable, HttpService } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators/map';

@Injectable()
export class BuildingService {
  rentCafe =
    'https://api.rentcafe.com/rentcafeapi.aspx?requestType=apartmentavailability&apitoken=ODU0Nzk%3d-InaOhyAR1SE%3d&VoyagerPropertyCode=3609st';
  private readonly URL: string = this.configService.get<string>('URL');

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {}

  getAvailableUnits(id: string): Observable<any> {
    const units = this.httpService.get(this.rentCafe);
    return units;
  }

  // todo: move to a service
  getPromotions(id?: string) {
    const url = `${this.URL}voyager_property?_fields=acf`;
    const promos = this.httpService.get(url).pipe(
      map(response => {
        let promo = response.data.map(evt => {
          const val = evt.acf;
          return { ...val };
        });

        if (id) {
          promo = promo.filter(evt => (evt?.id).trim() === id.trim());
          return promo.length ? promo[0] : null;
        }
        return promo;
      }),
    );
    return promos.toPromise();
  }
  convertTime(date) {
    const dateTime = new Date(date);
    let hour = dateTime.getHours();
    let amPm = 'am';
    if (hour > 12) {
      hour = hour - 12;
      amPm = 'pm';
    }
    hour = hour > 12 ? hour - 12 : hour;
    const minutes = String(dateTime.getMinutes()).padStart(2, '0');
    return `${hour}:${minutes}${amPm}`;
  }

  getWorkingHours(val) {
    const days = [
      'Mon',
      'Tues',
      'Wed',
      'Thu',
      'Fri',
      'Sat',
      'Sun',
      'Mon-Fri',
      'Sat-Sun',
    ];
    const start = this.convertTime(val.StartTime);
    const end = this.convertTime(val.EndTime);
    return `${days[val.Iday - 1]}: ${start}-${end} `;
  }

  determineAvailability(date): string {
    const today = new Date();
    const avail = new Date(date);
    if (avail > today) {
      return date;
    } else {
      return 'Available';
    }
  }

  private calculateFreeMonthPrice(price: number, monthSpecials: any): number {
    const { length_of_lease, number_of_free_months } = monthSpecials;
    var price =
      (price * (length_of_lease - number_of_free_months)) / length_of_lease;
    return Math.ceil(price);
  }

  private createSpecials(price: number) {
    const specialsObj = {
      min: price,
      max: price,
      special: price,
      MaximumRent: price,
      MinimumRent: price,
    };

    return specialsObj;
  }
  public checkIfSpecial(apartmentName: string) {
    if (apartmentName?.indexOf('*') > -1) return apartmentName.replace('*', '');
    return null;
  }

  checkSpecials(unit:any, promos: any, id: string) {
    let unitSpecial = {
      min: Math.floor(unit.MinimumRent),
      max: Math.floor(unit.MaximumRent),
      special: null,
      Specials: unit.Specials,
      MinimumRent: Math.floor(unit.MinimumRent),
      MaximumRent: Math.floor(unit.MaximumRent),
      availability: this.determineAvailability(unit.AvailableDate),
    };
    if (unit.Specials) {
      const _special = parseFloat(unit.Specials);
      if (!isNaN(_special)) {
        unitSpecial['special'] = Math.floor(_special);
      }
    }

    // const floorplanName = this.checkIfSpecial(unit.FloorplanName);
    /** * the following line checks if there is a Special property from the data that comes from rentCafe endpoint */
    // if (!isNaN(unit.Specials)) {
    //   unitSpecial['floorplanName'] = unit.FloorplanName;
    //   unitSpecial['FloorplanName'] = unit.FloorplanName;
    //   if (!specials || isNaN(specials)) unit.Specials = max;
    //   const calculatedSpecials = this.handleSpecials(
    //     Math.floor(unit.Specials),
    //     id,
    //     max,
    //     promos?.month_specials,
    //   );
    //   unitSpecial = { ...unitSpecial, ...calculatedSpecials, Specials: unit.Specials, specials: unit.Specials };
    // }

    return unitSpecial;
  }
  handleSpecials(specials: any, id: string, max: number, monthSpecials?: any) {
    if (
      monthSpecials?.length_of_lease &&
      monthSpecials?.number_of_free_months &&
      specials
    ) {
      const calculatedPrice = this.calculateFreeMonthPrice(max, monthSpecials);
      let specialsObj = this.createSpecials(calculatedPrice);
      specialsObj['specials'] = max;
      return specialsObj;
    } else if (specials) {
      let specialsObj = this.createSpecials(specials);
      if (id === '175se') specialsObj['specials'] = max;
      return specialsObj;
    }
  }
}
