// Angular Core
import { Component, Input, OnDestroy, OnInit } from '@angular/core';

// RxJs
import { catchError, Subscription, throwError } from 'rxjs';

// Services
import { MainSettingsService } from 'src/app/services/mainSettings/main-settings.service';
import { ManageBuyerService } from 'src/app/services/manageBuyer/manage-buyer.service';
import { ManageSupplierService } from 'src/app/services/manageSupplier/manage-supplier.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';
import { AuthorizedStatesService } from 'src/app/services/authorizedStates/authorized-states.service';

// Interfaces
import { saveMainSettingsInterface } from 'src/app/interfaces/common-interfaces';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';

@Component({
  standalone: false,
  selector: 'app-document',
  templateUrl: './document.component.html',
  styleUrls: ['./document.component.scss']
})
export class DocumentComponent implements OnInit, OnDestroy {

  @Input() doc!:string;
  @Input() user!:any;
  @Input() supplier!:any;
  @Input() view!:string;
  @Input() text!:any;
  @Input() type!:string;
  @Input() buttonText!:string;
  @Input() inRowItem!:boolean;
  @Input() authType!:string;
  sitename!: string;
  sitenameListener!: Subscription;

  constructor(
    private utilities:UtilitiesService, 
    private manageSupplier: ManageSupplierService,
    private authorizedStatesService : AuthorizedStatesService,
    private manageBuyer:ManageBuyerService,
    private mainSettings: MainSettingsService,
    private dataTransmitter: DataTransmitterService
    ) { }

  buttonClass!:string;
  buttonLabel!:string;

  ngOnInit(): void {
    this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename) => {
      this.sitename = sitename;
    });

    this.buttonClass = 'btn-xs btn-warning btn-font';
    this.buttonLabel = !this.buttonText ? "Download" : this.buttonText;
    
    if (typeof(this.inRowItem) !== 'undefined' && this.inRowItem) {
      this.buttonClass = 'btn btn-warning apply-for-account';
    } 
    if (typeof(this.buttonText) !== 'undefined') {
      this.buttonLabel = this.buttonText;
    }
  }

  /**
   * Generate File to view or download
   * @param {json} data
   * @param {string} action
   * @returns {undefined}
   */
  generateFile(data:any, action:string) {
    if(data.contents) {
        var fileData = data.contents;
        var fileExt = data.fileExt;
        var binary = atob(fileData.replace(/\s/g, ''));
        var len = binary.length;
        var buffer = new ArrayBuffer(len);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < len; i++) {
            view[i] = binary.charCodeAt(i);
        }
        var filename = data.filename;
        var blob = new Blob([view], {type: this.utilities.getFileType(fileExt)});
        let navigator: any = window.navigator;
        if (navigator.msSaveOrOpenBlob) { // a.click() won't work on IE or Edge
            navigator.msSaveBlob(blob, filename);
        } else {
            var url = URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }
    }
  };

  viewUniversalAppSubscribe!:Subscription;
  viewDocumentSubscribe!:Subscription;
  saveMainSettingsSubscribe!:Subscription;
  viewLicenseSubscribe!:Subscription;

  /**
   * Download requested document Supplier Info
   * @param {string} doc
   * @param {int} user
   * @param {int} supplier
   * @returns {undefined}
   */
  viewApp (doc:string, user:number, supplier:number) {
    this.viewUniversalAppSubscribe = this.manageSupplier.viewUniversalApp(doc, user, supplier)
    .pipe(
      catchError(() => {
        return throwError(() => new Error('ups sommething happend'));
      })
    )
    .subscribe({
      next: (res: any) => {
        this.generateFile(res.data, 'download')
      },
      error: (err) => {
        this.manageSupplier.errorCallBack(err);
      },
      complete: () => { },
    })
  };

  /**
   * Download requested document Buyer Info
   * @param {string} doc
   * @param {int} user
   * @returns {undefined}
   */
  viewDocument (doc:string, user:number) {
    this.viewDocumentSubscribe = this.manageBuyer.viewDocument(doc, user)
    .pipe(
      catchError(() => {
        return throwError(() => new Error('ups sommething happend'));
      })
    )
    .subscribe({
      next: (res: any) => {
        this.generateFile(res.data, 'download');
      },
      error: (err) => {
        this.manageBuyer.errorCallBack(err);
      },
      complete: () => { },
    })
  };

    /**
    * Method to view Supplier Authorized State License Document  
    * @param int stateCode
    * @param string authType
    * @returns void
    */
    viewAuthStateLicense(stateCode:number, authType:string) {
        var dataSet = {"auth_type" : authType, "state_code" : stateCode};
        this.viewLicenseSubscribe = this.authorizedStatesService.viewLicenseDocument(dataSet)
        .subscribe({
        next: (res: any) => {
          this.generateFile(res.data, 'view');
        },
        error: (err) => {
          this.authorizedStatesService.errorCallBack(err);
        },
        complete: () => { },
        });
    };
  
  /**
   * View requested document Main settings
   * @param {string} doc
   * @returns {undefined}
   */
  viewSuppDoc (doc:string) {
    var DataSet = {"document":doc};
    this.saveMainSettingsSubscribe = this.mainSettings.saveMainSettings(DataSet)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: saveMainSettingsInterface) => {
          this.generateFile(res.data, 'view');
        },
        error: (err) => {
          this.mainSettings.errorCallBack(err);
        },
        complete: () => { },
      })
 };

 ngOnDestroy(){
  this.viewUniversalAppSubscribe?.unsubscribe();
  this.viewDocumentSubscribe?.unsubscribe();
  this.saveMainSettingsSubscribe?.unsubscribe();
  this.sitenameListener.unsubscribe();
 }

}