import { TravelerModal } from '@profile-lib/index';
import { Timeouts } from '@utility-lib/index';

const notificationsSelectors = {
  notificationsURL: '/app/user2/profile?tab=notifications',
  notificationCheckbox: (index: number) => `mat-checkbox#mat-checkbox-${index}`,
  notificationChart: '.ta-notifications__body-wrapper'
};

export class NotificationsModal {
  static getNotificationsInfo(alias: string): void {
    cy.allure().logStep('Obtain latest notifications settings');
    cy.get(notificationsSelectors.notificationChart).should('be.visible');
    cy.intercept('PATCH', 'api/user/notificationPreferences/groups').as(`${alias}`);
    cy.get(this.getNotificationCheckbox(2)).as('notificationCheckbox');
    cy.get('@notificationCheckbox').click();
    cy.get('@notificationCheckbox').click();
    cy.wait('@' + alias).then((interception) => {
      // Gets current notification settings and saves them as aliases
      const response = interception.response;
      if (response) {
        const properties = [
          'BOOKING_CONFIRMATIONS_MY_OWN_TRIPS',
          'BOOKING_CONFIRMATIONS_TRIPS_FOR_ME',
          'FLIGHT_CHECK_IN'
        ];
        const channels = ['PUSH', 'SMS', 'EMAIL'];
        properties.forEach((property) => {
          channels.forEach((channel) => {
            cy.wrap(response.body.userPreferences[property].channels[channel])
              .should('have.property', 'enabled')
              .as(`${alias}_${property}_${channel}_Enabled`);
          });
        });
      }
    });
  }

  static visitNotificationsPage(): void {
    cy.allure().logStep('Visit notifications settings page');
    cy.visit(notificationsSelectors.notificationsURL);
  }

  static changeNotificationSettings(email: number, push: number, sms: number): void {
    cy.allure().logStep('Changing notifiction settings');
    cy.get(this.getNotificationCheckbox(email)).click();
    cy.get(this.getNotificationCheckbox(push)).click();
    cy.get(this.getNotificationCheckbox(sms)).click();
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
  }

  static compareNotificationSettings(): void {
    cy.allure().logStep('Comparing old settings with updated settings');
    const values = {
      Initial_BOOKING_CONFIRMATIONS_MY_OWN_TRIPS_EMAIL_Enabled:
        'Updated_BOOKING_CONFIRMATIONS_MY_OWN_TRIPS_EMAIL_Enabled',
      Initial_BOOKING_CONFIRMATIONS_TRIPS_FOR_ME_PUSH_Enabled:
        'Updated_BOOKING_CONFIRMATIONS_TRIPS_FOR_ME_PUSH_Enabled',
      Initial_FLIGHT_CHECK_IN_SMS_Enabled: 'Updated_FLIGHT_CHECK_IN_SMS_Enabled'
    };
    for (const [orgProp, newProp] of Object.entries(values)) {
      TravelerModal.compareAPIProperties(orgProp, newProp);
    }
  }

  static getNotificationCheckbox(index: number): string {
    return notificationsSelectors.notificationCheckbox(index);
  }
}
