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';

import { Response } from 'src/app/hmg-common/services/models/response';

@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';
  private static SERVICE_URL = 'https://hmgwebservices.com/PayOneDev/Pay_Request.aspx';
  public static paymentStatusURL = 'Services/PayOne.svc/REST/PayOneGetRequestsByProjectServiceAndItem';

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

  public getPaymentLanguageID(): number {
    return TranslatorService.getCurrentLanguageName() == 'en' ? 1 : 0;
  }

  public getPaymentStatus(transactionID: string, onError: any, errorLabel: string):
    Observable<Response> {
    const request = new PaymentValidationRequest();
    request.MerchantModuleSessionID = transactionID;
    request.PayOneProject = 0;
    request.PayOneService = 4;
    request.LanguageID = this.getPaymentLanguageID();
    this.authService.authenticateRequest(request);
    return this.con.postNoLoad(PaymentService.paymentStatusURL, request, onError);
  }

  public openPayment(amount: number, transactionID: string, orderDesc: string): Observable<boolean> {
    return Observable.create(observer => {
      // const transactionID = this.guid.generate();
      this.cs.openBrowser(this.generateURL(amount, orderDesc, transactionID),
        () => this.notifyCallerDone(observer, true),
        () => this.notifyCallerDone(observer, false),
        () => this.notifyCallerDone(observer, true),
        ['success'  ]);
      // 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, 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('ORDER_DESCRIPTION_VALUE', orderDesc);
    form = form.replace('SESSION_ID_VALUE', transactionID);
    form = form.replace('REQUEST_ID_VALUE', transactionID);
    form = form.replace('PROJECT_ID_VALUE', 'ENTED');
    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="ProjID" value="PROJECT_ID_VALUE">' +
      '<input type="hidden" name="PaymentDesc" value="ORDER_DESCRIPTION_VALUE">' +
      '<input type="hidden" name="sessID" value="SESSION_ID_VALUE">' +
      '<input type="hidden" name="reqID" value="REQUEST_ID_VALUE">' +
      '<input type="hidden" name="PayType" value="0">' +
      '<input type="hidden" name="langID" value="' + (TranslatorService.getCurrentLanguageName() == 'en' ? '1' : '0') + '"  >' +
      '<input type="hidden" name="ResponseContinueURL" value="http://hmg.com/Documents/success.html" >' +
      '<input type="hidden" name="BackClickUrl" value="http://hmg.com/Documents/success.html" >' +
      '</form>' +
      '<script type="text/javascript"> document.getElementById("paymentForm").submit(); </script>' +
      '</body>' +
      '</html>';
  }
}
