import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { BehaviorSubject } from "rxjs";

declare var convert: Function;
@Injectable()
export class OtpServicesService {
  private urlService: string;
  private urlServiceValidate: string;
  public sessionID: string;
  public validateStatus: boolean;
  private ip: string;
  private token: string;
  private response: boolean = false;
  private idUser;
  private tdUser;

  constructor(private http: HttpClient) {}

  get getConvert() {
    return convert;
  }

  generateOtpPublic(identification, typeDocument) {
    this.idUser = identification;
    this.tdUser = typeDocument;
    this.ip = (document.getElementById("ip") as HTMLInputElement).value;

    const param = {
      appOrigen: "wu",
      ip: this.ip,
      operacion: "generar",
      portlet: "otp",
      requestId: this.getID(),
      seguridad: {
        numeroDocumento: this.idUser,
        sessionId: this.sessionID,
        tipoDocumento: this.tdUser,
      },
    };

    let request = {
      datos: convert(JSON.stringify(param), this.token, true),
    };

    const headers = new HttpHeaders({
      "Content-Type": "application/json;charset=UTF-8",
      token: this.token,
    });
    return this.http.post(this.urlService, request, { headers: headers });
  }

  validateOtpPublic(otp) {
    const param = {
      appOrigen: "wu",
      ip: this.ip,
      codigoOtp: otp,
      operacion: "validar",
      portlet: "otp",
      requestId: this.getID(),
      seguridad: {
        numeroDocumento: this.idUser,
        sessionId: this.sessionID,
        tipoDocumento: this.tdUser,
      },
    };

    let request = {
      datos: convert(JSON.stringify(param), this.token, true),
    };

    const headers = new HttpHeaders({
      "Content-Type": "application/json;charset=UTF-8",
      token: this.token,
    });
    return this.http.post(this.urlServiceValidate, request, {
      headers: headers,
    });
  }

  setUrl(url) {
    this.urlService = url;
  }

  setUrlValidar(url) {
    this.urlServiceValidate = url;
  }

  setValidateToken(validateStatus: boolean) {
    this.validateStatus = validateStatus;
  }

  public setToken(token) {
    this.token = token;
  }

  public getToken() {
    return this.token;
  }

  public setResponse(response) {
    this.response = response;
  }

  public getResponse() {
    //this.resp.next({response: this.response});
    return this.response;
  }

  private getID() {
    return (
      this.S4() +
      this.S4() +
      "-" +
      this.S4() +
      "-4" +
      this.S4().substr(0, 3) +
      "-" +
      this.S4() +
      "-" +
      this.S4() +
      this.S4() +
      this.S4()
    ).toLowerCase();
  }

  private S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
}
