import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { PaymentInfoModel } from './models/payment-info.model';
import { PaymentValidationRequest } from './models/payment-validation.request';
import { PaymentValidationResponse } from './models/payment-validation.response';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { ConnectorService } from 'src/app/hmg-common/services/connector/connector.service';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { GuidService } from 'src/app/hmg-common/services/guid/guid.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';

@Injectable({
  providedIn: 'root'
})
export class PaymentService {

  public static MADA = 'MADA';
  public static MASTERCARD = 'MASTERCARD';
  public static SADAD = 'SADAD ';
  public static VISA = 'VISA';
  public static INSTALMENT = 'INSTALMENT';
  public static validateURL = 'Services/PayFort_Serv.svc/REST/GetRequestStatusByRequestID';
  private static SERVICE_URL = 'https://hmgwebservices.com/PayFortWeb/pages/SendPayFortRequest.aspx';

  constructor(
    public cs: CommonService,
    public ts: TranslatorService,
    public con: ConnectorService,
    public authService: AuthenticationService,
    public guid: GuidService
  ) { }


  public validatePayment(transactionID: string, onError: any, errorLabel: string): Observable<PaymentValidationResponse> {
    const request = new PaymentValidationRequest();
    request.ClientRequestID = transactionID;
    // this.authService.authenticateRequest(request);
    return this.con.post(PaymentService.validateURL, request, onError, errorLabel);
  }


  public openPayment(amount: number, method: string, orderDesc: string, ): Observable<boolean> {
    return Observable.create(observer => {
        const transactionID = this.guid.generate();
        this.cs.openBrowser( this.generateURL( amount, method, orderDesc, transactionID) ,
        () =>  this.notifyCallerDone(observer, true) ,
        () =>  this.notifyCallerDone(observer, false) );
        // this.hmgBrowser.registerBack(() => this.notifyCaller(observer, amount, transactionID));
        // this.hmgBrowser.registerClose(() => this.notifyCaller(observer, amount, transactionID));
    });
  }

  private notifyCaller(observer: any, amount: number, transactionID: string) {
    observer.next(new PaymentInfoModel(amount, transactionID)) ;
    observer.complete();
  }

  private notifyCallerDone(observer: any,done: boolean) {
    observer.next( done) ;
    observer.complete();
  }

  private generateURL( amount: number, method: string, orderDesc: string, transactionID: string): string {
    let form = this.getForm();
    const user = this.authService.getAuthenticatedUser();
    if (user) {
      form = form.replace('EMAIL_VALUE', user.Email || user.EmailAddress);
    }
    form = form.replace('AMOUNT_VALUE', (amount || 0 ).toString());
    form = form.replace('METHOD_VALUE', method);
    form = form.replace('ORDER_DESCRIPTION_VALUE', orderDesc);
    form = form.replace('ORDER_ID_VALUE', transactionID);
    form = form.replace('SERVICE_URL_VALUE', PaymentService.SERVICE_URL);
    console.log(form);
    const base64URL = 'data:text/html;base64,' + btoa(form);
    console.log(base64URL);
    return base64URL;
  }

  public getForm(): string {
    return '<html> ' +
      '<head></head>' +
      '<body>' +
      '<form id="paymentForm" action="SERVICE_URL_VALUE" method="post">' +
      '<input type="hidden" name="Amount" value="AMOUNT_VALUE">' +
      '<input type="hidden" name="ServID" value="2">' +
      '<input type="hidden" name="Email" value="EMAIL_VALUE">' +
      '<input type="hidden" name="PaymentOption" value="METHOD_VALUE">' +
      '<input type="hidden" name="Order_Desc" value="ORDER_DESCRIPTION_VALUE">' +
      '<input type="hidden" name="OrderID" value="ORDER_ID_VALUE">' +
      '<input type="hidden" name="ChannelID" value="3">' +
      '<input type="hidden" name="ProjID" value="0">' +
      '<input type="hidden" name="Lang" value="en" >' +
      '<input type="hidden" name="ReturnURL" value="' + TranslatorService.getCurrentLanguageName() + '" >' +
      '</form>' +
      '<script type="text/javascript"> document.getElementById("paymentForm").submit(); </script>' +
      '</body>' +
      '</html>';
  }
}
