import { Timeouts } from '@utility-lib/index';
import { TrainCheckout, TrainItinerary } from '@train-lib/index';
import { Logs } from '@utility-lib/log';

const trainExchangeSelector = {
  legChange: '[id="changeButton"]',
  searchButton: '.search-form-x-v2__bot',
  changeDate: '[icon="chevron-right"]',
  continueToCheckout: '[qaid="trainNextButton"]',
  changeNowButton: '.train-checkout-summary__payment__button',
  successMessage: '[data-testid="bookingSuccessModalTitle"]',
  dateTrigger: '[data-testid="dateTriggerV2FormattedDate"]',
  legTime: '[class="rail-leg__time--day1"]'
};

export class TrainExchange {
  static legChange(legChange = 0) {
    cy.allure().logStep('choose trip leg to be exchanged');
    cy.get(trainExchangeSelector.legTime, Timeouts.MEDIUM_TIMEOUT_30_SEC).should('be.visible');
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
    cy.get('body').then(($body) => {
      if ($body.text().includes(' Departure ')) {
        cy.get(trainExchangeSelector.legTime)
          .eq(0)
          .invoke('text')
          .then((dateFoundInExchange) => {
            cy.log(dateFoundInExchange);
            cy.task('getDataFromCache', 'departureDate').then((departureDateText: any) => {
              cy.log(departureDateText);
              cy.log(dateFoundInExchange);
              expect(departureDateText.trim()).to.equal(dateFoundInExchange.trim());
            });
          });
      } else if ($body.text().includes(' Return ')) {
        cy.get(trainExchangeSelector.legTime)
          .eq(1)
          .invoke('text')
          .then((returnDateFoundInExchange) => {
            cy.log(returnDateFoundInExchange);
            cy.task('getDataFromCache', 'returnDate').then((returnDateText: any) => {
              cy.log(returnDateText);
              cy.log(returnDateFoundInExchange);
              expect(returnDateText.trim()).to.equal(returnDateFoundInExchange.trim());
            });
          });
      }
    });
    cy.get(trainExchangeSelector.legChange).eq(legChange).contains('Change').click();
    cy.allure().logStep('trip leg chosen successfully ');
  }

  static searchTrips(legChange = 0) {
    cy.allure().logStep('change date to next day ');
    cy.wait('@waitForChangeCheckout').then((xhr) => {
      Logs.cypressResponseLog('RESPONSE', xhr);
    });
    cy.wait('@waitForTravellers');

    const getDateText = (type: string) => {
      cy.get(trainExchangeSelector.dateTrigger)
        .invoke('text')
        .then((dateText) => {
          cy.log(dateText);
          cy.task('getDataFromCache', type).then((cacheText: any) => {
            cy.log(cacheText);
            cy.log(dateText);
            expect(cacheText.trim()).to.equal(dateText.trim());
          });
        });
    };

    if (legChange === 0) {
      getDateText('departureDate');
    }

    if (legChange === 1) {
      getDateText('returnDate');
    }

    cy.get(trainExchangeSelector.changeDate).click();
    cy.allure().logStep(' date changed to next day');
    cy.allure().logStep('click on search button');
    cy.get(trainExchangeSelector.searchButton).contains('Search').click();
    cy.wait('@waitForChangeCheckout').then((xhr) => {
      Logs.cypressResponseLog('RESPONSE', xhr);
    });
    cy.allure().logStep('search button clicked');
  }
  static continueToCheckout() {
    cy.allure().logStep('choose fare and click on continue to checkout');
    cy.get(trainExchangeSelector.continueToCheckout).click();
    cy.wait('@waitForChangeCheckout');
    cy.allure().logStep('continue to checkout button clicked');
  }

  static changeCheckout(bookingFailed = false) {
    cy.allure().logStep('exchange checkout page loaded');
    TrainCheckout.skipSeatMaps();
    TrainCheckout.seatPreferences();
    TrainCheckout.selectTicketType('E-ticket');
    TrainCheckout.acceptAcknowledgement();
    cy.allure().logStep('click change now button');
    cy.get(trainExchangeSelector.changeNowButton).contains('Change now').click();
    cy.allure().logStep('change now button clicked');
    cy.wait('@waitForBookingStatusUpdate').then((xhr) => {
      Logs.cypressResponseLog('RESPONSE', xhr);
    });
    // cy.wait(60000);
    cy.get('body').then(($body) => {
      if ($body.find('[class="ta-modal-body"] [text="Edit search"]').length > 0) {
        cy.get('[class="ta-modal-body"] [text="Edit search"]').click();
        TrainExchange.legChange(0);
        this.searchTrips();
        this.continueToCheckout();
        TrainCheckout.acceptAcknowledgement();
        cy.get(trainExchangeSelector.changeNowButton).contains('Change now').click();
        cy.allure().logStep('change now button clicked');
      }
    });
    cy.get(trainExchangeSelector.successMessage, Timeouts.MAX_TIMEOUT_120_SEC).should(
      'have.text',
      'Train booking confirmed!'
    );
    cy.allure().logStep('exchange was done successfully ');
  }

  static processExchangeWorkflow(eTicket: string, legChange = 0, bookingFailed = false) {
    TrainItinerary.expectETicketIsDownloadable();
    cy.contains(`${eTicket}`);
    TrainItinerary.reloadItinerary();
    TrainItinerary.exchangeTicket();
    this.legChange(legChange);
    this.searchTrips(legChange);
    this.continueToCheckout();
    this.changeCheckout(bookingFailed);
  }
}
