import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { ReceiptService } from '../receipt.service';
import { Order} from '../order/order.model';
import { Observable }  from 'rxjs';
import { faCheck, faHourglass, faArrowUpRightFromSquare } from '@fortawesome/free-solid-svg-icons';

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

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

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

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

export class InvoiceComponent implements OnInit {
	faCheck = faCheck;
	faHourglass = faHourglass;
	faArrowUpRightFromSquare = faArrowUpRightFromSquare;
	orderId;
	public orderUpdate: Observable<Order>;
	public nameUpdate: Observable<string>;
	name: string = '';
	error: boolean = false;
	codeString: string = 'Test';
	invString: string = '';
	public isWCOrder : boolean = false;
	zcashUrl: SafeUrl = '';
	externalURL: string = '';
	order:Order = {
		_id: '',
		address: '',
		session: '',
		timestamp: '',
		closed: false,
		currency: '',
		price: 0,
		total: 0,
		totalZec: 0,
		paid: false,
		externalInvoice: '',
		shortCode: '',
		lines: [
			{
				qty: 1,
				name: '',
				cost:0
			}
		]
	};
	// -------------------------------------
	//
	// Language Support
	//
	vE = {
		invoiceInvoiceLbl : '',
		invoiceOrderId : '',
		invoiceOrderDate : '',
		invoiceZcashPrice : '',
		invoiceQtyLbl : '',
		invoiceOrderPrice : '',
		invoiceInvoiceTotal : '',
		invoicePaymentConfirmed : '',
		invoicePaymentPending : '',
		invoiceScanQrcode : '',
		invoiceCantScan : '',
		invoiceUseThis : '',
		invoiceWalletLink : '',
		invoiceDotOr : '',
		invoiceCopyAddress : '',
		invoiceCopyAmount : '',
		invoiceCopyMemo : '',
		invoiceReturnToshop : '',
		invoiceCopyNotavail : '',
		invoiceNotservClose : '',
		invoiceNotservError : '',
		invoiceCopyaddressError : '',
		invoiceCopyamountError : '',
		invoiceCopymemoError : '',
		invoiceInvalidId : '',
		invoiceInfoNotavail : ''
	};
	//
	constructor(
		private _ActiveRoute:ActivatedRoute,
		private router: Router,
		private sanitizer: DomSanitizer,
		public receiptService: ReceiptService,
		private notifierService : NotifierService,
		private languageService : LanguageService
	) {
		this.orderId = this._ActiveRoute.snapshot.paramMap.get("orderId");
		console.log('constructor - orderId -> ' + this.orderId);
		this.orderUpdate = receiptService.orderUpdate;
		this.nameUpdate = receiptService.nameUpdate;
		receiptService.getOrderById(this.orderId!).subscribe(response => {
			if (response.status == 200){
				this.error = false;
				if( response.body!.order.session.substring(0,1) == 'X') {
					this.invString = response.body!.order.externalInvoice;
					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.invString)))}`; 
				} else {
					this.codeString = `zcash:${response.body!.order.address}?amount=${response.body!.order.totalZec.toFixed(8)}&memo=${URLSafeBase64.encode(Buffer.from('ZGo Order::'.concat(this.orderId!)))}`; 
				}
				var qrcode = new QRCode(document.getElementById("payment-qr"), {
					text: this.codeString,
					logo: "/assets/zcash.png",
					width: 180,
					height: 180,
					logoWidth: 50,
					logoHeight: 50,
					correctLevel: QRCode.CorrectLevel.H
				});
				this.error = false;
			} else {
				this.error = true;
				this.codeString = 'Test';
			}
		});
		this.orderUpdate.subscribe(order => {
			this.order = order;
			if ( order.session.substring(0,1) == 'W') {
				this.isWCOrder = true;
			}
			this.zcashUrl = this.sanitizer.bypassSecurityTrustUrl(this.codeString);
		});
		this.nameUpdate.subscribe(name => {
			this.name = name;
		});
	}

	ngOnInit(): void {
		this.chgUILanguage();
	}

	backToShop() {
		if ( this.isWCOrder ) {
			//			console.log('External Invoice -> ' + this.order.externalInvoice );
			const b64URL:string = this.order.externalInvoice.substring(0,this.order.externalInvoice.indexOf("-"));
			//			console.log('encodedURL -> ' + b64URL );
			const shopURL: string = Buffer.from(b64URL, 'base64').toString();
			const tmp_orderid = this.order.externalInvoice.substring(this.order.externalInvoice.indexOf('-')+1);
			const wc_order_key = tmp_orderid.substring(tmp_orderid.indexOf('-')+1);
			const wc_orderid = tmp_orderid.substring(0,tmp_orderid.indexOf('-'));
			//	        console.log('wc_order_id -> ' + wc_orderid);
			//	        console.log('wc_order_key -> ' + wc_order_key);
			//			console.log('new URL -> ' +  shopURL + '/checkout/order-received/' + wc_orderid + '/?key=' + wc_order_key);
			if ( shopURL ) {
				//				console.log('Opening URL....' +  shopURL);
				window.open( shopURL + '/checkout/order-received/' + wc_orderid + '/?key=' + wc_order_key,"_blank");
			}	
		}
	}

	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.invoiceCopyNotavail,
				this.vE.invoiceNotservClose,
				'error',
				this.vE.invoiceNotservError);
		}
		try {
			navigator.clipboard.writeText(this.order.address);
		} catch (err) {
			this.notifierService
			.showNotification(
				this.vE.invoiceCopyaddressError, 
				this.vE.invoiceNotservClose,
				'error',
				this.vE.invoiceNotservError);
				//       console.error("Error", err);
		}
	}

	copyAmount() {
		if (!navigator.clipboard) {
			//       alert("Copy functionality not supported");
			this.notifierService
			.showNotification(
				this.vE.invoiceCopyNotavail,
				this.vE.invoiceNotservClose,
				'error',
				this.vE.invoiceNotservError);
		}
		try {
			navigator.clipboard.writeText(this.order.totalZec.toString());
		} catch (err) {
			this.notifierService
			.showNotification(
				this.vE.invoiceCopyamountError,
				this.vE.invoiceNotservClose,
				'error',
				this.vE.invoiceNotservError);
				//       console.error("Error", err);
		}
	}

	copyMemo() {
		if (!navigator.clipboard) {
			//       alert("Copy functionality not supported");
			this.notifierService
			.showNotification(
				this.vE.invoiceCopyNotavail,
				this.vE.invoiceNotservClose,
				'error',
				this.vE.invoiceNotservError);
		}
		try {
			navigator.clipboard.writeText("ZGo Order::" + this.order._id);
		} catch (err) {
			this.notifierService
			.showNotification(
				this.vE.invoiceCopymemoError,
				this.vE.invoiceNotservClose,
				'error',
				this.vE.invoiceNotservError);
				//       console.error("Error", err);
		}
	}

	chgUILanguage(){
		console.log('INVOICE.chgUILanguage Called ');
		this.languageService.getViewElements('invoice').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.invoiceInvoiceLbl = response.data.invoice_invoice_lbl;
				this.vE.invoiceOrderId = response.data.invoice_order_id;
				this.vE.invoiceOrderDate = response.data.invoice_order_date;
				this.vE.invoiceZcashPrice = response.data.invoice_zcash_price;
				this.vE.invoiceQtyLbl = response.data.invoice_qty_lbl;
				this.vE.invoiceOrderPrice = response.data.invoice_order_price;
				this.vE.invoiceInvoiceTotal = response.data.invoice_invoice_total;
				this.vE.invoicePaymentConfirmed = response.data.invoice_payment_confirmed;
				this.vE.invoicePaymentPending = response.data.invoice_payment_pending;
				this.vE.invoiceScanQrcode = response.data.invoice_scan_qrcode;
				this.vE.invoiceCantScan = response.data.invoice_cant_scan;
				this.vE.invoiceUseThis = response.data.invoice_use_this;
				this.vE.invoiceWalletLink = response.data.invoice_wallet_link;
				this.vE.invoiceDotOr = response.data.invoice_dot_or;
				this.vE.invoiceCopyAddress = response.data.invoice_copy_address;
				this.vE.invoiceCopyAmount = response.data.invoice_copy_amount;
				this.vE.invoiceCopyMemo = response.data.invoice_copy_memo;
				this.vE.invoiceReturnToshop = response.data.invoice_return_toshop;
				this.vE.invoiceCopyNotavail = response.data.invoice_copy_notavail;
				this.vE.invoiceNotservClose = response.data.invoice_notserv_close;
				this.vE.invoiceNotservError = response.data.invoice_notserv_error;
				this.vE.invoiceCopyaddressError = response.data.invoice_copyaddress_error;
				this.vE.invoiceCopyamountError = response.data.invoice_copyamount_error;
				this.vE.invoiceCopymemoError = response.data.invoice_copymemo_error;
				this.vE.invoiceInvalidId = response.data.invoice_invalid_id;
				this.vE.invoiceInfoNotavail = response.data.invoice_info_notavail;

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

}
