import { CardPaymentClientCallbackEvents } from './../enums/card-payment-client-callback-events.enum';
import { JsSdkUrl } from "../enums/js-sdk-url.enum";
import { CardPaymentInstrument } from "../interfaces/card-payment/card-payment-instrument.interface";

declare const securePayUI: any;

export class CardPaymentClient {

  private securePayUI : any;
  private sandbox     : boolean;
  private clientId    : string;
  private merchantCode: string;
  private containerId : string;
  private callback   ?: Function;
  private scriptId    : string;

  public securePayUiLoaded: boolean = false;

  constructor(options: {
    sandbox       : boolean,
    clientId      : string,
    merchantCode  : string,
    containerId   : string,
    callback     ?: (event: CardPaymentClientCallbackEvents, response?: any) => void
  }) {
    options.callback && (this.callback = options.callback);
    this.sandbox      = options.sandbox;
    this.clientId     = options.clientId;
    this.merchantCode = options.merchantCode;
    this.containerId  = options.containerId;
    const scriptEl    = document.createElement('script');
    this.scriptId     = 'securepay-js-id-' + new Date().getTime().toString();
    scriptEl.id       = this.scriptId;
    scriptEl.onload   = () => {
      this.init();
    };
    scriptEl.src = this.sandbox ? JsSdkUrl.SANDBOX_UI : JsSdkUrl.UI;
    document.head.appendChild(scriptEl); 
  }

  /**
   * Initial
   */
  private init() {
    this.securePayUI = new securePayUI.init({
      containerId : this.containerId,
      scriptId    : this.scriptId,
      clientId    : this.clientId,
      merchantCode: this.merchantCode,
      card: { // card specific config and callbacks
        onTokeniseSuccess: (tokenisedCard: CardPaymentInstrument) => {
          this.callback && this.callback(CardPaymentClientCallbackEvents.ON_TOKENISE_SUCCESS, tokenisedCard);
        },
        onTokeniseError: (errors: any) => {
          this.callback && this.callback(CardPaymentClientCallbackEvents.ON_TOKENISE_ERROR, errors);
        },
        onCardTypeChange: (cardType: any) => {
          this.callback && this.callback(CardPaymentClientCallbackEvents.ON_CARD_TYPE_CHANGE, cardType);
        },
        onBINChange: (cardBIN: any) => {
          this.callback && this.callback(CardPaymentClientCallbackEvents.ON_BIN_CHANGE, cardBIN);
        },
        onFormValidityChange: (valid: boolean) => {
          this.callback && this.callback(CardPaymentClientCallbackEvents.ON_FORM_VALIDITY_CHANGE, valid);
        },
      },
      onLoadComplete: () => {
        this.securePayUiLoaded = true;
        this.callback && this.callback(CardPaymentClientCallbackEvents.ON_LOAD_COMPLETE);
      }
    });
  }

  /**
   * Fire Tokenise
   */
  public tokenise() {
    this.securePayUI.tokenise();
  }

}