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';

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';
    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
				}
			]
		};

	constructor(
		private _ActiveRoute:ActivatedRoute,
		private router: Router,
    	private sanitizer: DomSanitizer,
		public receiptService: ReceiptService,
   		private notifierService : NotifierService 
	) {
		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;
				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.codeString = `zcash:${this.order.address}?amount=${this.order.totalZec.toFixed(8)}&memo=${URLSafeBase64.encode(Buffer.from('ZGo Order::'.concat(this.orderId!)))}`; 
      		this.zcashUrl = this.sanitizer.bypassSecurityTrustUrl(this.codeString);
		});
		this.nameUpdate.subscribe(name => {
			this.name = name;
		});
	}

	ngOnInit(): void {
    }

	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("Copy functionality not supported","Close","error");
      }
      try {
         navigator.clipboard.writeText(this.order.address);
      } catch (err) {
         this.notifierService
             .showNotification("Error copying address","Close","error");
//       console.error("Error", err);
      }
    }

    copyAmount() {
      if (!navigator.clipboard) {
//       alert("Copy functionality not supported");
         this.notifierService
             .showNotification("Copy functionality not supported","Close","error");
      }
      try {
         navigator.clipboard.writeText(this.order.totalZec.toString());
      } catch (err) {
         this.notifierService
             .showNotification("Error while copying ammount","Close","error");
//       console.error("Error", err);
      }
    }

    copyMemo() {
      if (!navigator.clipboard) {
//       alert("Copy functionality not supported");
         this.notifierService
             .showNotification("Copy functionality not supported","Close","error");
      }
      try {
         navigator.clipboard.writeText("ZGo Order::" + this.order._id);
      } catch (err) {
         this.notifierService
             .showNotification("Error while copying Memo","Close","error");
//       console.error("Error", err);
      }
    }

}
