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 { LanguageService } from '../language.service';
import { LanguageData } from '../language.model';

@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,
      paid: false,
      zats: false,
      invoices: false,
      expiration: new Date(Date.now()).toISOString(),
      payconf: false,
      crmToken: ''
    };

  _ordersOk = false;

  range = new FormGroup({
    start: new FormControl<Date | null>(null),
    end: new FormControl<Date | null>(null),
  });
  // -------------------------------------
  //
  // Language Support
  //
  vE = {
      dbexportSettingsTitle : '',
      dbexportExportDescrip : '',
      dbexportDateRange : '',
      dbexportStartDate : '',
      dbexportEndDate : '',
      dbexportInvalidStart : '',
      dbexportInvalidEnd : '',
      dbexportNoordersCreated : '',
      dbexportNothingTodo : '',
      dbexportBtnClose : '',
      dbexportDownloadLink : '',
      dbexportFileHeader : '',
      dbexportClosedYes : '',
      dbexportClosedNo : '',
      dbexportPaidYes : '',
      dbexportPaidNo : ''
  };
  //

  constructor(private languageService : LanguageService,
              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.chgUILanguage();
    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 = this.vE.dbexportFileHeader + "\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 ? this.vE.dbexportClosedYes : this.vE.dbexportClosedNo ;
/*
           console.log('Order No. ' + 
                       this.orders[i]._id! + ' - totalZec = ' + 
                       this.orders[i].totalZec);
*/
           var paid = this.orders[i].paid ?  this.vE.dbexportPaidYes  : this.vE.dbexportPaidNo ;
           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();
  }

  chgUILanguage(){
    console.log('DBEXPORT.chgUILanguage Called ');
    this.languageService.getViewElements('dbexport').subscribe(
        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.dbexportSettingsTitle = response.data.dbexport_settings_title;
            this.vE.dbexportExportDescrip = response.data.dbexport_export_descrip;
            this.vE.dbexportDateRange = response.data.dbexport_date_range;
            this.vE.dbexportStartDate = response.data.dbexport_start_date;
            this.vE.dbexportEndDate = response.data.dbexport_end_date;
            this.vE.dbexportInvalidStart = response.data.dbexport_invalid_start;
            this.vE.dbexportInvalidEnd = response.data.dbexport_invalid_end;
            this.vE.dbexportNoordersCreated = response.data.dbexport_noorders_created;
            this.vE.dbexportNothingTodo = response.data.dbexport_nothing_todo;
            this.vE.dbexportBtnClose = response.data.dbexport_btn_close;
            this.vE.dbexportDownloadLink = response.data.dbexport_download_link;
            this.vE.dbexportFileHeader = response.data.dbexport_file_header;
            this.vE.dbexportClosedYes = response.data.dbexport_closed_yes;
            this.vE.dbexportClosedNo = response.data.dbexport_closed_no;
            this.vE.dbexportPaidYes = response.data.dbexport_paid_yes;
            this.vE.dbexportPaidNo = response.data.dbexport_paid_no;

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

}
