import { Headers, RequestOptions, Http } from '@angular/http';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Component, OnInit, EventEmitter, Output } from '@angular/core';

@Component({
    selector: 'wallet-one',
    templateUrl: './wallet-one.component.html',
    styleUrls: ['wallet-one.component.scss']
})
export class WalletOneComponent implements OnInit {
    
    @Output() formSaved = new EventEmitter();
    walletOneForm: FormGroup;

    constructor(private fb: FormBuilder) {
        this.walletOneForm = fb.group({
            WMI_MERCHANT_ID: '109183878583',
            WMI_CURRENCY_ID: '840',
            WMI_PAYMENT_NO: '1',
            WMI_DESCRIPTION: '',
            WMI_SUCCESS_URL: 'https://localhost:3000/payments',
            WMI_FAIL_URL: 'https://localhost:3000/payments',
            WMI_PTENABLED: [
                'CreditCardUSD'
            ],
            WMI_SIGNATURE: '',
            deliveryRequired: false,
            payMethod: this.payMethod
        });
     }

     nextStep() {
         this.formSaved.next(this.walletOneForm.value);
     }

    ngOnInit() { }

    payMethod(dal, data) {
        delete data.paymentForm.payMethod;
        delete data.deliveryForm;
        let paymentKey = dal.addPaymentRequest(data, "WALLET_ONE").key;
        return dal.listenPaymentResponse(paymentKey).map(response => {
            if(response.token){
                let token = response.token;
                console.log(token);
                data.paymentForm.WMI_SIGNATURE = token;
                data.paymentForm.WMI_PAYMENT_AMOUNT = data.orderForm.totalPrice;
                console.log(data.paymentForm);
            } else {
                data.paymentForm.WMI_SIGNATURE = "";
                data.paymentForm.WMI_PAYMENT_AMOUNT = data.orderForm.totalPrice;
            }
            return data;
        }).filter(response => {
            return data.paymentForm.WMI_SIGNATURE !== '';
        });
    }
}