import { Inject, Component, OnInit, ViewEncapsulation} from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

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

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

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

export class CheckoutComponent implements OnInit{
	address: string;
	total: number;
	orderId: string;
	codeString: string = '';
	zcashUrl: SafeUrl;
	
	constructor(
		private dialogRef: MatDialogRef<CheckoutComponent>,
		private sanitizer: DomSanitizer,
		@Inject(MAT_DIALOG_DATA) public data: { totalZec: number, addr: string, orderId: string},
		private notifierService : NotifierService ) {
	
		console.log("Entra a Constructor")
		this.address = data.addr;
		this.total = data.totalZec;
		this.orderId = data.orderId;
		this.codeString = `zcash:${this.address}?amount=${this.total.toFixed(8)}&memo=${URLSafeBase64.encode(Buffer.from('ZGo Order::'.concat(this.orderId)))}`; 
		this.zcashUrl = this.sanitizer.bypassSecurityTrustUrl(this.codeString);
	}

	ngOnInit() {
		var qrcode = new QRCode(document.getElementById("checkout-qr"),
			{ 
		        text: this.codeString,
				logo: "/assets/zcash.png",
				width: 230,
				height: 230,
				logoWidth: 60,
				logoHeight: 60,
		        correctLevel: QRCode.CorrectLevel.H
	    	});
	    console.log("mgOnInit - pasa");

	}

	confirm() {
		this.dialogRef.close(true);
	}

	close() {
		this.dialogRef.close(false);
	}

	copyAddress() {
		if (!navigator.clipboard) {
//			alert("Copy functionality not supported");
			this.notifierService
			    .showNotification("Copy functionality not supported","Close","error");
		}
		try {
			navigator.clipboard.writeText(this.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.total.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.orderId);
		} catch (err) {
			this.notifierService
			    .showNotification("Error while copying Memo","Close","error");
//			console.error("Error", err);
		}
	}
}
