import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from "@angular/router";
import { HttpClient, HttpParams, HttpHeaders } from "@angular/common/http";
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { PmtData } from "./pmtservice.model";
import { XeroInvoice } from "./xeroinvoice.model";
import { Order } from '../order/order.model'
import { ConfigData } from '../configdata';
import { faCheck, faHourglass } from '@fortawesome/free-solid-svg-icons';

import { NotifierService } from '../notifier.service';

var QRCode = require('easyqrcodejs');
var URLSafeBase64 = require('urlsafe-base64');
var Buffer = require('buffer/').Buffer;

import { LanguageService } from '../language.service';

@Component({
	selector: 'app-pmtservice',
	templateUrl: './pmtservice.component.html',
	styleUrls: ['./pmtservice.component.css']
})

export class PmtserviceComponent implements OnInit {

	faCheck = faCheck;
	faHourglass = faHourglass;

	beUrl = ConfigData.Be_URL;
	private reqHeaders: HttpHeaders = new HttpHeaders();

	public shop: string = '';
	public pmtData : PmtData = {
		ownerId :'',
		invoice: '',
		amount: 0,
		currency: '',
		shortcode: ''
	};

	public invData : XeroInvoice = { 
		inv_Type : '',
		inv_Id : '',
		inv_No : '',
		inv_Contact : '',
		inv_Currency : '',
		inv_CurrencyRate : 0,
		inv_Status : '',
		inv_Total : 0,
		inv_Date : new Date(),
		inv_shortCode : '',
		inv_ProcDate : new Date()
	};


	public order: Order = {
		_id : '',
		address: '',
		session: '',
		timestamp: '',
		closed: false,
		currency: '',
		price: 0,
		total: 0,
		totalZec: 0,
		paid: false,
		externalInvoice: '',
		shortCode: '',
		token: '',
		lines: [
			{
				qty: 1,
				name: '',
				cost:0
			}
		]
	};

	private invData_raw : string = '';
	private invData_buff : any = null;

	public reportType = 0;
	public Status = 0;

	codeString: string = 'ZGo - The Zcash Register';
	zcashUrl: SafeUrl = '';
	zPrice: number = 1.0;
	name: string = '';
	error: boolean = false;
	orderId : string = '';
	// -------------------------------------
	// Language Support
	//
	vE = {
		pmtserviceInvalidOwnerid : '',
		pmtserviceNotservClose : '',
		pmtserviceNotservError : '',
		pmtserviceCopyNotavail : '',
		pmtserviceCopyaddressError : '',
		pmtserviceCopyamountError : '',
		pmtserviceCopymemoError : '',
		pmtservicePaymentNotprocessed : '',
		pmtservicePmtsrvNot : '',
		pmtserviceEnabledFor : '',
		pmtserviceConnectoXero : '',
		pmtserviceServerFailed : '',
		pmtserviceInvoiceNum : '',
		pmtserviceInvoiceNotfound : '',
		pmtserviceInvoiceInvalid : '',
		pmtserviceInvoicePaid : '',
		pmtserviceInvoiceCurrency : '',
		pmtserviceCurrencyNotsup : '',
		pmtserviceAmountDoesnot : '',
		pmtserviceMatchValue : '', 
		pmtserviceReportedByxero : '',
		pmtserviceHdrTxt1 : '',
		pmtserviceHdrTxt2 : '',
		pmtserviceHdrTxt3 : '',
		pmtserviceZecdataPrice : '',
		pmtserviceZecdataTotal : '',
		pmtserviceInvoiceItem : '',
		pmtserviceInvoiceQty : '',
		pmtserviceInvoicePrice : '',
		pmtserviceInvoiceTotal : '',
		pmtservicePaymentConfirmed : '',
		pmtservicePaymentPending : '',
		pmtserviceScanQrcode : '',
		pmtserviceCantScan : '',
		pmtserviceUseThis : '',
		pmtserviceWalletLink : '',
		pmtserviceCopyAddress : '',
		pmtserviceCopyAmount : '',
		pmtserviceCopyMemo : ''
	}
	//
	constructor(private activatedRoute : ActivatedRoute,
				private http : HttpClient,
				private sanitizer: DomSanitizer,
				private notifierService : NotifierService,
				private languageService : LanguageService  ){
		var auth = 'Basic ' + Buffer.from(ConfigData.UsrPwd).toString('base64');
		this.reqHeaders = new HttpHeaders().set('Authorization', auth);
		this.activatedRoute.queryParams.subscribe((params) => {
			this.pmtData.ownerId = params["owner"];
			this.pmtData.invoice = params["invoiceNo"];
			this.pmtData.amount = +params["amount"];
			this.pmtData.currency = params["currency"];
			this.pmtData.shortcode = params["shortCode"];
			this.getInvoiceData( this.pmtData );
		});
		this.chgUILanguage();
	}

	ngOnInit() {
	}

	getInvoiceData( reqData : PmtData ) { 
		//this.getXeroInvoiceData( reqData );
		let obs = this.http.post<{reportType: number, order: Order, shop: string}>
		(this.beUrl+'invdata', 
		 {payload: reqData},
		 {headers: this.reqHeaders, observe: 'response' }
		);
		obs.subscribe((invoiceData) => {
			if(invoiceData.status == 201) {
				this.reportType = invoiceData.body!.reportType;
				this.order = invoiceData.body!.order;
				this.shop = invoiceData.body!.shop;
				this.orderId = String(this.order._id);

				//         console.log('Generating QRCode....')

				this.codeString = `zcash:${this.order.address}?amount=${this.order.totalZec.toFixed(8)}&memo=${URLSafeBase64.encode(Buffer.from('ZGo Order::'.concat(this.orderId).concat(' Invoice: ').concat(this.order.externalInvoice)))}`; 

				var qrcode = new QRCode(document.getElementById("invoice-qr"), {
					text: this.codeString,
					logo: "/assets/zcash.png",
					width: 180,
					height: 180,
					logoWidth: 50,
					logoHeight: 50,
					correctLevel: QRCode.CorrectLevel.H
				});

				this.zcashUrl = this.sanitizer.bypassSecurityTrustUrl(this.codeString);
			} else {
				this.reportType = invoiceData.body!.reportType;
				console.log('reportType ' + invoiceData.body!.reportType + ' code ' + invoiceData.status);
			}
		});
	}

	getIconStyle(order : Order) {
		if( order.paid )
			return "font-size: 14px; color: #72cc50; margin-bottom: -2px;";
		return "color: #FB4F14; margin-bottom: -2px; cursor: pointer;";

	}

	copyAddress() {
		if (!navigator.clipboard) {
			//       alert("Copy functionality not supported");
			this.notifierService
			.showNotification(this.vE.pmtserviceCopyNotavail,
							  this.vE.pmtserviceNotservClose,
							  "error",
							  this.vE.pmtserviceNotservError);
		}
		try {
			navigator.clipboard.writeText(this.order.address);
		} catch (err) {
			this.notifierService
			.showNotification(this.vE.pmtserviceCopyaddressError,
							  this.vE.pmtserviceNotservClose,
							  "error",
							  this.vE.pmtserviceNotservError);
							  //       console.error("Error", err);
		}
	}

	copyAmount() {
		if (!navigator.clipboard) {
			//       alert("Copy functionality not supported");
			this.notifierService
			.showNotification(this.vE.pmtserviceCopyNotavail,
							  this.vE.pmtserviceNotservClose,
							  "error",
							  this.vE.pmtserviceNotservError);
		}
		try {
			navigator.clipboard.writeText(this.order.totalZec.toString());
		} catch (err) {
			this.notifierService
			.showNotification(this.vE.pmtserviceCopyamountError,
							  this.vE.pmtserviceNotservClose,
							  "error",
							  this.vE.pmtserviceNotservError);
							  //       console.error("Error", err);
		}
	}

	copyMemo() {
		if (!navigator.clipboard) {
			//       alert("Copy functionality not supported");
			this.notifierService
			.showNotification(this.vE.pmtserviceCopyNotavail,
							  this.vE.pmtserviceNotservClose,
							  "error",
							  this.vE.pmtserviceNotservError);
		}
		try {
			navigator.clipboard.writeText("ZGo Order::" + this.orderId + " Invoice: " + this.order.externalInvoice);
		} catch (err) {
			this.notifierService
			.showNotification(this.vE.pmtserviceCopymemoError,
							  this.vE.pmtserviceNotservClose,
							  "error",
							  this.vE.pmtserviceNotservError);
							  //       console.error("Error", err);
		}
	}

	chgUILanguage(){
		console.log('PMTSERVICE.chgUILanguage Called ');
		this.languageService.getViewElements('pmtservice').subscribe(
			response => { 
				console.log('Received >> ', response );
				console.log('Language Code : ', response.language);
				console.log('Component Name : ',response.component);
				console.log('Language data : ',response.data);

				this.vE.pmtserviceInvalidOwnerid = response.data.pmtservice_invalid_ownerid;
				this.vE.pmtserviceNotservClose = response.data.pmtservice_notserv_close;
				this.vE.pmtserviceNotservError = response.data.pmtservice_notserv_error;
				this.vE.pmtserviceCopyNotavail = response.data.pmtservice_copy_notavail;
				this.vE.pmtserviceCopyaddressError = response.data.pmtservice_copyaddress_error;
				this.vE.pmtserviceCopyamountError = response.data.pmtservice_copyamount_error;
				this.vE.pmtserviceCopymemoError = response.data.pmtservice_copymemo_error;
				this.vE.pmtservicePaymentNotprocessed = response.data.pmtservice_payment_notprocessed;
				this.vE.pmtservicePmtsrvNot = response.data.pmtservice_pmtsrv_not;
				this.vE.pmtserviceEnabledFor = response.data.pmtservice_enabled_for;
				this.vE.pmtserviceConnectoXero = response.data.pmtservice_connecto_xero;
				this.vE.pmtserviceServerFailed = response.data.pmtservice_server_failed;
				this.vE.pmtserviceInvoiceNum = response.data.pmtservice_invoice_num;
				this.vE.pmtserviceInvoiceNotfound = response.data.pmtservice_invoice_notfound;
				this.vE.pmtserviceInvoiceInvalid = response.data.pmtservice_invoice_invalid;
				this.vE.pmtserviceInvoicePaid = response.data.pmtservice_invoice_paid;
				this.vE.pmtserviceInvoiceCurrency = response.data.pmtservice_invoice_currency; 
				this.vE.pmtserviceCurrencyNotsup = response.data.pmtservice_currensy_notsup; 
				this.vE.pmtserviceAmountDoesnot = response.data.pmtservice_amount_doesnot;
				this.vE.pmtserviceMatchValue = response.data.pmtservice_match_value;
				this.vE.pmtserviceReportedByxero = response.data.pmtservice_reported_byxero;
				this.vE.pmtserviceHdrTxt1 = response.data.pmtservice_hdr_txt1;
				this.vE.pmtserviceHdrTxt2 = response.data.pmtservice_hdr_txt2;
				this.vE.pmtserviceHdrTxt3 = response.data.pmtservice_hdr_txt3;
				this.vE.pmtserviceZecdataPrice = response.data.pmtservice_zecdata_price;
				this.vE.pmtserviceZecdataTotal = response.data.pmtservice_zecdata_total;
				this.vE.pmtserviceInvoiceItem = response.data.pmtservice_invoice_item;
				this.vE.pmtserviceInvoiceQty = response.data.pmtservice_invoice_qty;
				this.vE.pmtserviceInvoicePrice = response.data.pmtservice_invoice_price;
				this.vE.pmtserviceInvoiceTotal = response.data.pmtservice_invoice_total;
				this.vE.pmtservicePaymentConfirmed = response.data.pmtservice_payment_confirmed;
				this.vE.pmtservicePaymentPending = response.data.pmtservice_payment_pending;
				this.vE.pmtserviceScanQrcode = response.data.pmtservice_scan_qrcode;
				this.vE.pmtserviceCantScan = response.data.pmtservice_cant_scan;
				this.vE.pmtserviceUseThis = response.data.pmtservice_use_this;
				this.vE.pmtserviceWalletLink = response.data.pmtservice_wallet_link;
				this.vE.pmtserviceCopyAddress = response.data.pmtservice_copy_address;
				this.vE.pmtserviceCopyAmount = response.data.pmtservice_copy_amount;
				this.vE.pmtserviceCopyMemo = response.data.pmtservice_copy_memo;

			},
			error  => { console.log('Error >> ',error); }
		);
	}  

}
