import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

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 { OrderService } from '../order/order.service';
import { NotifierService } from '../notifier.service';


@Component({
  selector: 'app-db-export',
  templateUrl: './db-export.component.html',
  styleUrls: ['./db-export.component.css']
})
 
export class DbExportComponent implements OnInit {

  public orders: Order[] = [];
  public ownerUpdate: Observable<Owner>;
  public ordersUpdate: Observable<Order[]>;
  fileUrl : any;
  owner : Owner = {
      address: '',
      name: '',
      currency: 'usd',
      tax: false,
      taxValue: 0,
      vat: false,
      vatValue: 0,
      first: '',
      last: '',
      email: '',
      street: '',
      city: '',
      state: '',
      postal: '',
      phone: '',
      paid: false,
      website: '',
      country: '',
      zats: false,
      invoices: false,
      expiration: new Date(Date.now()).toISOString(),
      payconf: false,
      viewkey: '',
      crmToken: ''
    };

  _ordersOk = false;

  range = new FormGroup({
    start: new FormControl<Date | null>(null),
    end: new FormControl<Date | null>(null),
  });

  constructor(private notifierService : NotifierService,
              private dialogRef: MatDialogRef<DbExportComponent>,
              private sanitizer: DomSanitizer,
              public orderService: OrderService,
              public userService: UserService) { 
    this.ownerUpdate = userService.ownerUpdate;
    this.orderService.getAllOrders();
    this.ordersUpdate = orderService.allOrdersUpdate;
  }

  ngOnInit(): void {
    console.log('db-export Init -->');
    this.owner = this.userService.currentOwner();
    console.log(this.owner.name);
    console.log(this.range);
    this.ordersUpdate.subscribe((orders) => {
      this.orders = orders;
//      console.log('Order -> ' + this.orders[0].timestamp);
      if( this.orders.length != 0 ) {
        this._ordersOk = true
      } 
    }); 
  }



  ordersOk() : boolean {
    return this._ordersOk;
  }

  checkReady() : boolean {
    var data : string = '';
    var chkRdy : boolean = false;
    if ( (this.range.value.start != null ) &&
         (this.range.value.end != null) ) {
         // process order list
          const formatter = new Intl.NumberFormat('en-US', {
             minimumFractionDigits: 8,      
             maximumFractionDigits: 8,
          });

         // create header
         data = '"Date","Order ID","Currency","Closed?","Amount","Rate","ZEC","Paid?","Invoice"' + "\n";

         var iniDate = new Date(this.range.value.start);
         var endDate = new Date(this.range.value.end);
         for (let i=0; i < this.orders.length; i++){
           var date = new Date(this.orders[i]!.timestamp!);
           var orderid = String(this.orders[i]._id);
           var closed = this.orders[i].closed ? 'Yes' : 'No';
/*
           console.log('Order No. ' + 
                       this.orders[i]._id! + ' - totalZec = ' + 
                       this.orders[i].totalZec);
*/
           var paid = this.orders[i].paid ? 'Yes' : 'No';
           if ( (date >= iniDate) && (date <= endDate) ) {
              data = data + 
                     date.getFullYear() + '-' +
                    (date.getMonth()+1).toString().padStart(2,'0') + '-' +
                    date.getDate().toString().padStart(2,'0') 
                    + ',' +
                    orderid + ',' +
                    this.orders[i].currency + ',' +
                    closed + ',' +
                    this.orders[i].total + ',' +
                    this.orders[i].price! + ',' +
                    this.orders[i].totalZec + ',' +
                    paid + ',"' +
                    this.orders[i].externalInvoice + '"' +
                    '\n';
           }  
          }
         const blob = new Blob([data], { type: 'application/octet-stream' });
         this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));         

         chkRdy = true;
    }        
    return chkRdy;
  }

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

}
