import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogConfig} from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { LineItem } from '../items/lineitem.model';
import { newLineItem } from '../items/newlineitem.model';
import { Order } from './order.model';
import { FullnodeService } from '../fullnode.service';
import { OrderService } from './order.service';
import { CancelComponent } from '../cancel/cancel.component';
import { CheckoutComponent} from '../checkout/checkout.component';
import { PromptInvoiceComponent } from '../prompt-invoice/prompt-invoice.component';
import { ReceiptQRComponent} from '../receipt-qr/receipt-qr.component';
import { faFileInvoiceDollar } from '@fortawesome/free-solid-svg-icons';

import { faTrash } from '@fortawesome/free-solid-svg-icons';
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons';
import { faChevronRight } from '@fortawesome/free-solid-svg-icons';
import { faSignOut } from '@fortawesome/free-solid-svg-icons';

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

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

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

export class OrderComponent implements OnInit{

	public oLines : newLineItem[] = [];
	public myLines : LineItem[] = [];

	faInvoice = faFileInvoiceDollar;
	public 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
			}
		]
	};
	public price: number = 1;
	public total: number = 0;
	public orderUpdate: Observable<Order>;
	public priceUpdate: Observable<number>;
	public totalUpdate: Observable<number>;

	// ------------------------------------
	//
	faTrash = faTrash;
	faTrashAlt = faTrashAlt;
	faChevronRight = faChevronRight;
	faSignOut = faSignOut;
	// -------------------------------------
    //
    // Language Support
    //
    vE = {
    	orderNoOpenorder : '',
    	orderCancelOrder : '',
    	orderConfirmCancel : '',
    	orderRemoveItem : '',
    	orderConfirmRemove : '',
    	orderConfirmRemove1 : '',
    	orderCancelOk : '',
    	orderNotservClose : '',
    	orderNotservSuccess : '',
    	orderTotalTitle : '',
    	orderItemLbl : '',
    	orderQtyLbl : '',
    	orderTotalLbl : '',
    	orderCancelBtn : '',
    	orderInvoiceBtn : '',
    	orderCheckoutBtn : ''
    }
    //
    // ------------------------------------------------------------
	constructor(
		private languageService : LanguageService,
		public fullnodeService: FullnodeService,
		public orderService: OrderService,
		private dialog: MatDialog,
		private notifierService: NotifierService )
	{
		this.priceUpdate = fullnodeService.priceUpdate;
		this.priceUpdate.subscribe((price) => {
			this.price = price;
		});
		this.orderUpdate = orderService.orderUpdate;
		this.orderUpdate.subscribe((order) => {
			this.order = order;

			//console.log('this.order > ' + JSON.stringify(this.order));
// ------------------------------------------------
			this.oLines = [];
			this.myLines = this.order.lines;
            var nl = {} as newLineItem;

			for ( let i = 0; i < this.myLines.length; i++ )
			{
//			   console.log("Loop : " + i + " - name : " + this.myLines[i].name);
			   nl = this.fillLineData(i,this.myLines[i].name,
			   	             this.myLines[i].qty,
			   	             this.myLines[i].cost) ;
//			   console.log(">> line_id: " + nl.line_id +
//			   			   " name: " + nl.name +
//			   			   " qty: " + nl.qty +
//			   			   " cost: " + nl.cost + " <<" 	
//			   	          )
			   this.oLines.push(nl);
               // this.oLines[i].cost = this.myLines[i].cost;
 			}
// ------------------------------------------------
		});
		this.totalUpdate = orderService.totalUpdate;
		this.totalUpdate.subscribe((total) => {
			this.total = total;
		});

	}

	ngOnInit() {
        this.chgUILanguage();
	}

	cancelOrder() {
		const dialogConfig = new MatDialogConfig();

		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {title: this.vE.orderCancelOrder, 
		                     msg: this.vE.orderConfirmCancel };

		const dialogRef = this.dialog.open(CancelComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
			if (val) {
				//console.log('Canceling');
				this.orderService.cancelOrder(this.order._id!).subscribe((response) => {
					this.orderService.getOrder();
				this.notifierService
				    .showNotification(this.vE.orderCancelOk,
			    	              this.vE.orderNotservClose,
			    	              'success',
			    	              this.vE.orderNotservSuccess);
				});
			}
			//else {
				//console.log('Returning to page');
			//}
			this.orderService.getOrder();
			this.oLines = [];
		});
	}

	checkout() {
		var zec = this.total/this.price;
		this.order.totalZec = parseFloat(zec.toFixed(8));
		const dialogConfig = new MatDialogConfig();
		
		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {
			totalZec: this.order.totalZec,
			addr: this.order.address,
			orderId: this.order._id
		};

		const dialogRef = this.dialog.open(CheckoutComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
			if (val) {
				const dialogConfig2 = new MatDialogConfig();
				dialogConfig2.disableClose = true;
				dialogConfig2.autoFocus = true;
				dialogConfig2.data = {
					order: this.order._id
				};
				console.log('Payment confirmed!');
				this.orderService.closeOrder(true);
				const dialogRef2 = this.dialog.open(ReceiptQRComponent, dialogConfig2);
				dialogRef2.afterClosed().subscribe( val => {
					if (val) {
						console.log('Receipt closed.');
						this.oLines = [];
					}
				});
			} else {
				console.log('Returning to order');
			}
		});
	}

	invoice() {
		var zec = this.total/this.price;
		this.order.totalZec = parseFloat(zec.toFixed(8));
		const dialogConfig = new MatDialogConfig();
		
		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {
			orderId: this.order._id
		};

        //console.log ('order_id :  ' + this.order._id);

		const dialogRef = this.dialog.open(PromptInvoiceComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
			if (val) {
				this.orderService.closeOrder(false);
				this.oLines = [];
			} else {
				console.log('Returning to order');
			}
		});
	}

	getCurrency(){
		return this.order.currency.toUpperCase();
	}


	fillLineData(i: number, 
		         iname: string,
		         iqty: number,
		         icost: number) : newLineItem {

		const a = { line_id: i, 
			        name: iname, 
			        qty: iqty, 
			        cost: icost } as newLineItem;
		return a;
	}

	trashCanClicked(item : newLineItem, lines: newLineItem[]) {

		const dialogConfig = new MatDialogConfig();

		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {title: this.vE.orderRemoveItem,
		                     msg: this.vE.orderConfirmRemove + 
		                          item.name + ' x ' + item.qty +
		                          this.vE.orderConfirmRemove1 };
		const dialogRef = this.dialog.open(CancelComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
			if (val) {
//				console.log('Deleting item at line: ' 
//					         + (item.line_id +1)
//					         + " => (" + item.name +")");
				this.orderService.updateOrder(item.line_id,lines);
				this.orderService.getOrder();
				if ( this.order.lines.length == 0 ) {
					this.orderService.cancelOrder(this.order._id!)
					                 .subscribe((response) => {
							this.orderService.getOrder();
						});	
				}
			} else {
				console.log('Returning to order');
			}
		});
	}

	chgUILanguage(){
        //console.log('ORDER.chgUILanguage Called ');
 		this.languageService.getViewElements('order').subscribe({
			next: 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.orderNoOpenorder = response.data.order_no_openorder;
			        this.vE.orderCancelOrder = response.data.order_cancel_order;
			        this.vE.orderConfirmCancel = response.data.order_confirm_cancel;
			        this.vE.orderRemoveItem = response.data.order_remove_item;
			        this.vE.orderConfirmRemove = response.data.order_confirm_remove;
			        this.vE.orderConfirmRemove1 = response.data.order_confirm_remove1; 
			        this.vE.orderCancelOk = response.data.order_cancel_ok;
			        this.vE.orderNotservClose = response.data.order_notserv_close;
			        this.vE.orderNotservSuccess = response.data.order_notserv_success;
			        this.vE.orderTotalTitle = response.data.order_total_title;
			        this.vE.orderItemLbl = response.data.order_item_lbl;
			        this.vE.orderQtyLbl = response.data.order_qty_lbl;
			        this.vE.orderTotalLbl = response.data.order_total_lbl;
			        this.vE.orderCancelBtn = response.data.order_cancel_btn;
			        this.vE.orderInvoiceBtn = response.data.order_invoice_btn;
			        this.vE.orderCheckoutBtn = response.data.order_checkout_btn;

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

}
