import { Component, OnInit } from '@angular/core';
import { ModalController, Platform } from '@ionic/angular';
import { PayPal, PayPalPayment, PayPalConfiguration } from '@ionic-native/paypal/ngx';

@Component({
    selector: 'app-checkout',
    templateUrl: './checkout.page.html',
    styleUrls: ['./checkout.page.scss'],
})
export class CheckoutPage implements OnInit {

    constructor(public modalController: ModalController, private payPal: PayPal) { }

    ngOnInit() {
    }

    dismiss() {
        // using the injected ModalController this page
        // can "dismiss" itself and optionally pass back data
        this.modalController.dismiss({
            'dismissed': true
        });
    }

    paymentAmount: string = '640';
    currency: string = 'USD';
    currencyIcon: string = 'USD';

    payWithPaypal() {
        this.payPal.init({
            PayPalEnvironmentProduction: 'YOUR_PRODUCTION_CLIENT_ID',
            PayPalEnvironmentSandbox: 'AVszPxWCuK3FGXKlgOCFu3gVXr8lFkKj9z1wUo9BYdestZbGRg5vDqWm_pqlLkhEu8KHsjP8NmfPhc_o'
        }).then(() => {
            // Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction
            this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({
                // Only needed if you get an "Internal Service Error" after PayPal login!
                //payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal
            })).then(() => {
                let payment = new PayPalPayment(this.paymentAmount, this.currency, 'Description', 'sale');
                this.payPal.renderSinglePaymentUI(payment).then((res) => {
                    console.log(res);
                    // Successfully paid
                }, (error) => {
                    console.log(error);
                    // Error or render dialog closed without being successful
                });
            }, (error) => {
                console.log(error);
                // Error in configuration
            });
        }, (error) => {
            console.log(error);
            // Error in initialization, maybe PayPal isn't supported or something else
        });
    }
}
