import { Hotels, hotelSearchResultSelector, SearchButtonType } from '@hotel-lib/index';
import { LocationUtility, Logs, Utility, utilitySelector } from '@utility-lib/index';

export interface HotelParams {
  countAttempt: number;
  isNeedToReselectLocation: boolean;
}

export class ReSearchUtility {
  static initHotelParams(): HotelParams {
    return {
      countAttempt: 0,
      isNeedToReselectLocation: false
    };
  }

  static increaseAttemptAndResetReselectLocation(hotelParams: HotelParams) {
    hotelParams.countAttempt++;
    hotelParams.isNeedToReselectLocation = false;
  }

  static switchLocationIfHotelSearchResultEmpty(hotelParams: HotelParams) {
    cy.get(utilitySelector.bodySelector).then((hotelNotFound) => {
      if (hotelNotFound.find(utilitySelector.warningMsg).length > 0) {
        this.changeHotelFromSearchPage(LocationUtility.getHotelUS(), hotelParams);
      }
    });
  }

  static changeHotelFromSearchPage(location: string, params: HotelParams) {
    if (params.countAttempt > 3) {
      throw new Error(
        `Cannot book hotel. Tried: ${params.countAttempt} times with different hotels`
      );
    }
    this.increaseAttemptAndResetReselectLocation(params);
    const message = `>>>>>>>>>> Change Hotel/Location to: ${location}. Attempt: ${params.countAttempt} <<<<<<<<< `;
    Logs.logToCypressAndAllure(message);
    this.changeHotelLocation(location);
    Hotels.searchHotel(SearchButtonType.HEADER, params);
    Utility.expectSearchLoaderDisabled();
  }

  static changeHotelLocation(location: string) {
    cy.allure().logStep(`Change Hotel/Location: ${location}`);
    cy.get(hotelSearchResultSelector.hotelSearchHeader).click();
    cy.wait('@waitForHotelSearch');
    Hotels.selectHotelLocation(location);
  }
}
