import {Component, Input, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {AlertModal} from '../../utils/modal/alert';
import {ReportsService} from '../../services/reports.service';
import {ModalLoading} from '../../utils/modal/loading.component';
import {PiwikService} from '../../utils/piwik/piwik.service';
import {EnvProperties} from '../../utils/properties/env-properties';
import {ErrorCodes} from '../../utils/properties/errorCodes';

import 'rxjs';
import {Subscriber} from "rxjs";
import {properties} from "../../../../environments/environment";

@Component({
  selector: 'search-download',
  template: `
      <button [attr.uk-tooltip]="'title: Download' + ((totalResults > csvLimit)?' the first 2000 ':' ') + 'results.' + 
        ((totalResults > csvLimit && properties.zenodoDumpUrl)?' To get all results download the data dump. ':' ') " 
        class="uk-button uk-button-link uk-flex uk-flex-middle" [class.uk-disabled]="isDisabled"
        [disabled]="isDisabled"
        (click)="downloadfile(downloadURLAPI+'?format=csv'+csvParams,type+'-report-'+((totalResults > csvLimit)?'2000 ':totalResults))">
        <icon name="download" [flex]="true"></icon>
      </button>
      <modal-loading></modal-loading>
      <modal-alert #AlertModalCsvError></modal-alert>
  `
})

export class SearchDownloadComponent {
  @Input() isDisabled: boolean = false;
  @Input() totalResults: number = 0;
  @Input() csvParams: string;
  @Input() type: string;
  @ViewChild(AlertModal) alertApplyAll: AlertModal;
  downloadURLAPI: string;

  public csvLimit: number = 0;

  @ViewChild(ModalLoading) loading: ModalLoading;
  // Alert box when something is wrong with CSV requests
  @ViewChild('AlertModalCsvError') alertCsvError;
  public properties: EnvProperties;
  public errorCodes: ErrorCodes = new ErrorCodes();
  subscriptions = [];

  constructor(private route: ActivatedRoute, private _reportsService: ReportsService, private _piwikService: PiwikService) {
  }

  ngOnInit() {
    this.properties = properties;
    this.csvLimit = this.properties.csvLimit;
    this.downloadURLAPI = this.properties.csvAPIURL;
  }

  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }

  denialOfDownload() {
    this.alertApplyAll.cancelButton = true;
    this.alertApplyAll.okButton = false;
    this.alertApplyAll.alertTitle = "Download Results in CSV";
    this.alertApplyAll.message = "Sorry, but the results are too many! Use the api instead!";
    this.alertApplyAll.cancelButtonText = "Ok";
    this.alertApplyAll.open();

    console.error("Error downloading file. Results are too many!");
    //this.handleError("Error downloading file. Results are too many!", err);
  }

  downloadfile(url: string, filename: string) {
    //var newWindow = window.open("", "_parent");
    //var newWindow = window.open();
    //console.log("Downloading file: "+ url);
    this.openLoading();
    this.setMessageLoading("Downloading CSV file");

    this.subscriptions.push(this._reportsService.downloadCSVFile(url).subscribe(
        data => {
          this.closeLoading();
          //window.open(window.URL.createObjectURL(data),filename+".csv");
          //console.info("Fill window with data for csv");
          if (typeof document !== 'undefined') {
            var url = window.URL.createObjectURL(data);
            var a = window.document.createElement('a');
            window.document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = filename + ".csv";
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove(); // remove the element
          }
          //newWindow.location.assign(window.URL.createObjectURL(data));

          //window.location.href = window.URL.createObjectURL(data);

          this.subscriptions.push(this._piwikService.trackDownload(this.properties, "searchDownload").subscribe());
        },
        error => {
          //console.error("Error downloading the file.");
          this.handleError("Error downloading file: " + filename, error);

          //newWindow.close();
          this.closeLoading();
          this.confirmOpenCsvError();
        }/*,
          () => {
            console.log('Completed file download.');
            //setTimeout(function(){ newWindow.close(); }, 500);
          }*/
    ));
  }


  public openLoading() {
    if (this.loading) {
      this.loading.open();
    }
  }

  public closeLoading() {
    if (this.loading) {
      this.loading.close();
    }
  }

  public setMessageLoading(message: string) {
    if (this.loading) {
      this.loading.message = message;
    }
  }

  public confirmOpenCsvError() {
    this.alertCsvError.cancelButton = false;
    this.alertCsvError.okButton = true;
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
    this.alertCsvError.okButtonText = "OK";
    this.alertCsvError.open();
  }

  private handleError(message: string, error) {
    console.error("Search Download (component): " + message, error);
  }
}
