import { Injectable, NgZone } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Observable, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { StorageService } from 'src/app/services/storage.service';


declare var PagSeguroDirectPayment: any;


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

  SessionId: any;
  hashCode: any;
  cardToken: any;
  public carai :string; 
  
  creditCard = {
    num: '',
    cvv: '',
    monthExp: '',
    yearExp: '',
    brand: '',
    token: ''
};


  constructor(private http: HttpClient, private storageService: StorageService, public zone: NgZone) {
    this.SessionId = this.SessionId
    this.hashCode = this.hashCode
    this.cardToken = this.cardToken

  }

  carregaJavascriptPagseguro() {
    new Promise((resolve) => {
      let script: HTMLScriptElement = document.createElement('script');
      script.addEventListener('load', r => resolve());
      script.src = 'https://stc.sandbox.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js';
      document.head.appendChild(script);
    });

  }

  createSession() {

    const auth_token = this.storageService.getCurrentUser().token;
    const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': auth_token });

    return this.http.post('https://api.ticketin.com.br/api/orders/create-session', {}, { headers: headers })
      .pipe(map(res => this.SessionId = res));
  }

  setSession() {
    this.SessionId
    PagSeguroDirectPayment.setSessionId(this.SessionId.id)
  }

  getPaymentMethods() {
    PagSeguroDirectPayment.getPaymentMethods({
      success: function (response) { console.log('PaymentMethods',response); },
      error: function (response) { console.log('PaymentMethods',response); },
      complete: function (response) { console.log('PaymentMethods',response); }
    });

  }

  onSenderHashReady() {
    this.hashCode = PagSeguroDirectPayment.getSenderHash();
    return this.hashCode;
  }

  getBrand() {

    PagSeguroDirectPayment.getBrand({
      cardBin: '4111111111111111',
      success: function (response) {
        console.log('brand',response)
        //bandeira encontrada
      },
      error: function (response) {
        //tratamento do erro
        console.log('brand',response)

      },
      complete: function (response) {
        //tratamento comum para todas chamadas
        console.log('brand',response)

      }
    });

  }

  getInstallment() {
    PagSeguroDirectPayment.getInstallments({
      amount: 118.80,
      maxInstallmentNoInterest: 2,
      brand: 'visa',
      success: function (response) { console.log('Installment',response); },
      error: function (response) { console.log('Installment',response); },
      complete: function (response) { console.log('Installment',response); }
    });
  }

  getCreditCardToken(){
    PagSeguroDirectPayment.createCardToken({
      cardNumber: '4111111111111111', // Número do cartão de crédito
      brand: 'visa', // Bandeira do cartão
      cvv: '013', // CVV do cartão
      expirationMonth: '12', // Mês da expiração do cartão
      expirationYear: '2026', // Ano da expiração do cartão, é necessário os 4 dígitos.
        success: response => {
            this.creditCard.token = response.card.token
        }
    });
}


//   getCreditCardToken(): Promise<any> {
//     return new Promise((resolve, reject) => {
//         PagSeguroDirectPayment.createCardToken({
//           cardNumber: '4111111111111111', // Número do cartão de crédito
//           brand: 'visa', // Bandeira do cartão
//           cvv: '013', // CVV do cartão
//           expirationMonth: '12', // Mês da expiração do cartão
//           expirationYear: '2026', // Ano da expiração do cartão, é necessário os 4 dígitos.
//             success: (response) => {
//                 this.zone.run(() => {
//                     this.cardToken.token = response.card.token;
//                     resolve({token: response.card.token});
//                     console.log('token' , this.cardToken.token);
//                 });
//             },
//             error(error) {
//                 reject(error)
//             }
//         })
//     });
// }

//   getCreditCardToken(): Promise<any> {
//     return new Promise((resolve, reject) => {
//         PagSeguroDirectPayment.createCardToken({
//             cardNumber: '4111111111111111', // Número do cartão de crédito
//       brand: 'visa', // Bandeira do cartão
//       cvv: '013', // CVV do cartão
//       expirationMonth: '12', // Mês da expiração do cartão
//       expirationYear: '2026', // Ano da expiração do cartão, é necessário os 4 dígitos.
//             success: (response) => {
//               this.cardToken =  response
//                    resolve ()
//             },
//             error(error) {
//                 reject(error)
//             }
//         })
//     });
// }

  // createCardToken() {
  //   PagSeguroDirectPayment.createCardToken({
  //     cardNumber: '4111111111111111', // Número do cartão de crédito
  //     brand: 'visa', // Bandeira do cartão
  //     cvv: '013', // CVV do cartão
  //     expirationMonth: '12', // Mês da expiração do cartão
  //     expirationYear: '2026', // Ano da expiração do cartão, é necessário os 4 dígitos.
  //     success:  response => {  return this.carai = response.card.token },
  //     error: function (response) { return console.log(response)},
  //     complete: function (response) { return console.log(response) } 
  //   });

  //   console.log('epa', this.carai); 

  // }

  checkoutCreditCard() {

   // let token =  this.createCardToken()
    let sender_hash = this.onSenderHashReady()
    console.log('hash', sender_hash)

    console.log('tokencard', this.creditCard.token)

    let order = 
        {
        "event_id": 1,
        "payment_method": "creditCard",
        "orderCard": {
            "card_number": "4111111111111111",
            "card_holder": "Comprador teste",
            "expiration_month": "12",
            "expiration_year": "2030",
            "birth_date": "13/08/1990",
            "document": "10347252621",
            "phone": "31992037276",
            "zip_code": "32920000",
            "address": "Rua nula",
            "address_number": "sem",
            "address_complement": "",
            "address_neighborhood": "tereza",
            "address_city": "cidade",
            "address_state": "MG",
            "token": this.creditCard.token
        },
        "installment_quantity": 1,
        "ticket_quantity": 1,
        "sender_hash": sender_hash,
        "orderTickets": [
            {
                "event_lot_id": 1,
                "participant_name": "Rodrigo",
                "participant_email": "rodrigo-kall@hotmail.com"
            }
        ]
    };

    const auth_token = this.storageService.getCurrentUser().token;
    const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': auth_token });

    return this.http.post('https://api.ticketin.com.br/api/orders/checkout', order, { headers: headers })
      .pipe(
        map(result => {
          return result;
        }));


    //post /api/orders/checkout

   
  }

  checkoutDebito() {

    let sender_hash = this.onSenderHashReady()
    console.log(sender_hash)



    let order = {
      "event_id": 1,
      "payment_method": "online_debit",
      "bank_name": "itau",
      "ticket_quantity": 1,
      "sender_hash": sender_hash,
      "orderTickets": [
        {
          "event_lot_id": 1,
          "participant_name": "Rodrigo",
          "participant_email": "rodrigo-kall@hotmail.com"
        }
      ]
    }

    const auth_token = this.storageService.getCurrentUser().token;
    const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': auth_token });

    console.log(auth_token)

    return this.http.post('https://api.ticketin.com.br/api/orders/checkout', order, { headers: headers })
      .pipe(
        map(result => {
          return result;
        }));
  }

  checkoutBoleto(): Observable<any> {

    let sender_hash = this.onSenderHashReady()
    console.log(sender_hash)

    let order = {
      "event_id": 1,
      "payment_method": "boleto",
      "ticket_quantity": 1,
      "sender_hash": sender_hash,
      "orderTickets": [
        {
          "event_lot_id": 1,
          "participant_name": "Rodrigo",
          "participant_email": "rodrigo-kall@hotmail.com"
        }
      ]
    }

    const auth_token = this.storageService.getCurrentUser().token;
    const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': auth_token });

    console.log(auth_token)

    return this.http.post('https://api.ticketin.com.br/api/orders/checkout', order, { headers: headers })
      .pipe(
        map(result => {
          return result;
        }));
  }

  nofitication() {

    //post /api/orders/notifications

  }
}