import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs';
import { Order } from '../order/order.model';
import { FullnodeService } from '../fullnode.service';
import { UserService } from '../user.service';
import { Owner } from '../owner.model';
import { User } from '../user.model';
import { OrderService } from '../order/order.service';

import { MatDialog, MatDialogConfig} from '@angular/material/dialog';
import { PromptInvoiceComponent } from '../prompt-invoice/prompt-invoice.component';
import { PromptReceiptComponent } from '../prompt-receipt/prompt-receipt.component';
import { DbExportComponent } from '../db-export/db-export.component';

import { faTimes } from '@fortawesome/free-solid-svg-icons';
import { faTimesCircle } from '@fortawesome/free-solid-svg-icons';
import { faCheck } from '@fortawesome/free-solid-svg-icons';
import { faCheckCircle } from '@fortawesome/free-solid-svg-icons';
import { faHourglass } from '@fortawesome/free-solid-svg-icons';
import { faTrash } from '@fortawesome/free-solid-svg-icons';

import { LanguageService } from '../language.service';
import {SessionpayComponent} from '../sessionpay/sessionpay.component';

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

export class ListOrdersComponent implements OnInit, OnDestroy{
//	orderId;
	public todayTotal: number = 0;
	public total: number = 0;
	public orders: Order[] = [];
	public ownerUpdate: Observable<Owner>;
	public ordersUpdate: Observable<Order[]>;
    

	// ------------------------------------
	//
	faTimes = faTimes;
	faTimesCircle = faTimesCircle;
	faCheck = faCheck;
	faCheckCircle = faCheckCircle;
	faHourglass = faHourglass;
	faTrash = faTrash;
	payConf : boolean = false;
	owner : Owner = {
			address: '',
			name: '',
			currency: 'usd',
			tax: false,
			taxValue: 0,
			vat: false,
			vatValue: 0,
			paid: false,
			zats: false,
			invoices: false,
			expiration: new Date(Date.now()).toISOString(),
			payconf: false,
			crmToken: ''
		};
	zecPrice: number = 1;
	nodeAddress: string = '';
	session: string = '';
	addrUpdate: Observable<string>;
	priceUpdate: Observable<number>;
	userUpdate: Observable<User>;
	// -------------------------------------
	// -------------------------------------
	//
	// Language Support
	//
	vE = {
		listordersBacktoshopBtn : '',
		listordersExportOrders : '',
		listordersTodaysTotal : '',
		listordersOverallTotal : '',
		listordersOrderTotal : '',
		listordersOrderId : '',
		listordersItemLbl : '',
		listordersQtyLbl : '',
		listordersTotalLbl : '',
		listordersInvoiceBtn : '',
		listordersReceiptBtn : '',
		listordersNoOrders : '',
		listordersEndDate : ''
	}
	//

	constructor(
		private languageService : LanguageService,
		public orderService: OrderService,
		public userService: UserService,
		public fullnodeService: FullnodeService,
		private dialog: MatDialog)
	{
		this.ownerUpdate = userService.ownerUpdate;
		this.userUpdate = userService.userUpdate;
		this.orderService.getAllOrders();
		this.ordersUpdate = orderService.allOrdersUpdate;
		this.addrUpdate = fullnodeService.addrUpdate;
		this.priceUpdate = fullnodeService.priceUpdate;
		this.priceUpdate.subscribe(price => {
			this.zecPrice = price;
		});
		this.addrUpdate.subscribe(nAddress => {
			this.nodeAddress = nAddress;
		});
		this.userUpdate.subscribe(user => {
			this.session = user.session;
		});
	}

	ngOnInit(){
//		console.log('listOrders Init -->');
   	this.chgUILanguage();
		this.owner = this.userService.currentOwner();
//        console.log(this.owner.name);
        this.payConf = this.owner.payconf;
//        this.payConf = true;
//        console.log('payConf = ', this.payConf);

		this.ordersUpdate.subscribe((orders) => {
			this.total = 0;
			this.todayTotal = 0;
			var today = new Date();
			this.orders = orders;
	
			//console.log(this.ownerUpdate);
			for (let i=0; i < this.orders.length; i++){
				this.total += this.orders[i].totalZec;
			//

				var date = new Date(this.orders[i]!.timestamp!);
				var diff = (today.getTime() / 1000) - (date.getTime()/1000);
				if (diff < (24*3600)){
					this.todayTotal += this.orders[i].totalZec;
				}
			}
		});
	}

	ngOnDestroy(){
		this.total = 0;
		this.todayTotal = 0;
	}

	getIcon(order : Order) {
	    if( order.paid )
		  return faCheckCircle;
		return faHourglass;
	}

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

	}

	invoice(order : Order) {
//		var zec = this.total/this.price;
//		this.order.totalZec = parseFloat(zec.toFixed(8));
		const dialogConfig = new MatDialogConfig();
		
//		console.log("Order data:");
//		console.log(order);
//		console.log("order.total = " + order.total);

		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {
			orderId: order._id
		};

		const dialogRef = this.dialog.open(PromptInvoiceComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
				console.log('Returning to order list');
		});
	}

	receipt(order : Order) {
//		var zec = this.total/this.price;
//		this.order.totalZec = parseFloat(zec.toFixed(8));
		const dialogConfig = new MatDialogConfig();
		
//		console.log("Order data:");
//		console.log(order);
//		console.log("order.total = " + order.total);

		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {
			orderId: order._id
		};

		const dialogRef = this.dialog.open(PromptReceiptComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
				console.log('Returning to order list');
		});
	}

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

		//console.log('openDbExport ---');

		dialogConfig.disableClose = false;
		dialogConfig.autoFocus = true;
		dialogConfig.data = this.owner;

		const dialogRef = this.dialog.open(DbExportComponent, dialogConfig);
		dialogRef.afterClosed().subscribe((val) => {
				console.log('Returning to order list');
		});

	}

	chgUILanguage(){
		//console.log('LISTORDERS.chgUILanguage Called ');
		this.languageService.getViewElements('listorders').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.listordersBacktoshopBtn = response.data.listorders_backtoshop_btn;
				this.vE.listordersExportOrders = response.data.listorders_export_orders;
				this.vE.listordersTodaysTotal = response.data.listorders_todays_total;
				this.vE.listordersOverallTotal = response.data.listorders_overall_total;
				this.vE.listordersOrderId = response.data.listorders_order_id;
				this.vE.listordersOrderTotal = response.data.listorders_order_total;
				this.vE.listordersItemLbl = response.data.listorders_item_lbl;
				this.vE.listordersQtyLbl = response.data.listorders_qty_lbl;
				this.vE.listordersTotalLbl = response.data.listorders_total_lbl;
				this.vE.listordersInvoiceBtn = response.data.listorders_invoice_btn;
				this.vE.listordersReceiptBtn = response.data.listorders_receipt_btn;
				this.vE.listordersNoOrders = response.data.listorders_no_orders;
				this.vE.listordersEndDate = response.data.listorders_end_date;

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

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

	  dialogConfig.disableClose = true;
	  dialogConfig.autoFocus = true;
	  dialogConfig.data = {
		  addr: this.nodeAddress,
		  session: this.session,
		  zecPrice: this.zecPrice
	  };

	  const dialogRef = this.dialog.open(SessionpayComponent, dialogConfig);
  }
}
