import { TrainSearchResults } from '@train-lib/index';

const multiLegSelector = {
  railSummarySegments: '.rail-summary__segments',
  trainChange: '.train-change',
  farePrice: '.fare-price',
  segment: '.segment',
  submitButton: '[type="submit"]',
  routeInfoLogoContainerImg: '.route-info__logo-container img',
  taCard: '.ta-card'
};
export class MultiLegOption {
  static selectMultiLegOption() {
    cy.allure().logStep('Select Multi Leg Option');
    cy.get(multiLegSelector.railSummarySegments)
      .last()
      .invoke('text')
      .then((text) => {
        if (text.includes('change') || text.includes('changes')) {
          this.extractNoOfSegments().then((noOfSegments) => {
            this.putNoOfSegmentsInCacheAndClickSubmit(noOfSegments);
          });
        } else {
          cy.get(multiLegSelector.taCard).each(($card) => {
            if ($card.find(multiLegSelector.trainChange).length > 0) {
              cy.wrap($card).find(multiLegSelector.farePrice).click({ force: true });
              cy.get(multiLegSelector.railSummarySegments)
                .last()
                .should('contain', /change|changes/i)
                .then(() => {
                  this.clickCheckoutButton();
                });
            }
          });
        }
      });
  }

  static expectNoOfSegments(noOfSegments: number) {
    cy.allure().logStep('Expect No Of Segments');
    cy.get(multiLegSelector.segment).should('have.length', noOfSegments);
  }

  static selectDBOperator() {
    cy.allure().logStep('Select DB Operator');
    cy.get(multiLegSelector.taCard).each(($operator) => {
      const operatorLogos = $operator.find(multiLegSelector.routeInfoLogoContainerImg);
      const operatorNames = operatorLogos
        .map((index, logo) => (logo as HTMLImageElement).alt)
        .toArray();
      if (operatorNames.includes('DEUTSCHE_BAHN')) {
        cy.wrap($operator).find(multiLegSelector.farePrice).click({ force: true });
        this.clickCheckoutButton();
        return false;
      }
    });

    TrainSearchResults.getSegmentDetails();
    this.clickCheckoutButton();
  }

  static selectMultipleOperators() {
    cy.allure().logStep('Select Multiple Operators');
    cy.get(multiLegSelector.taCard).each(($operator) => {
      if ($operator.find(multiLegSelector.routeInfoLogoContainerImg).length > 1) {
        cy.wrap($operator).find(multiLegSelector.farePrice).click({ force: true });
        this.clickCheckoutButton();
        return false;
      }
    });
    TrainSearchResults.getSegmentDetails();
    this.clickCheckoutButton();
  }

  static selectDirectOption() {
    cy.allure().logStep('Select Direct Option');
    cy.get(multiLegSelector.railSummarySegments)
      .last()
      .invoke('text')
      .then((text) => {
        if (!text.includes('change') || !text.includes('changes')) {
          this.extractNoOfSegments().then((noOfSegments) => {
            this.putNoOfSegmentsInCacheAndClickSubmit(noOfSegments);
          });
        } else {
          cy.get(multiLegSelector.taCard).each(($card) => {
            if ($card.find(multiLegSelector.trainChange).length > 0) {
              cy.wrap($card).find(multiLegSelector.farePrice).click({ force: true });
              cy.get(multiLegSelector.railSummarySegments)
                .last()
                .should('contain', ' Direct ')
                .then(() => {
                  this.clickCheckoutButton();
                });
            }
          });
        }
      });
  }

  private static extractNoOfSegments() {
    cy.allure().logStep('Extract No Of Segments');
    return cy
      .get(multiLegSelector.trainChange)
      .invoke('text')
      .then((text) => {
        const matchResult = text.match(/\d+/);
        return matchResult !== null ? parseInt(matchResult[0]) : 0;
      });
  }

  private static putNoOfSegmentsInCacheAndClickSubmit(noOfSegments: number) {
    cy.allure().logStep('Put No Of Segments In Cache And Click Submit');
    cy.task('putDataInCache', {
      key: 'noOfSegments',
      data: noOfSegments
    });
    this.clickCheckoutButton();
  }

  static clickCheckoutButton() {
    cy.allure().logStep('Click Submit Button');
    cy.get(multiLegSelector.submitButton).click();
  }
}
