import { AddEitResponse } from './../models/add.eit.response';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { ModalController } from '@ionic/angular';


@Component({
  selector: 'app-add-attach',
  templateUrl: './add-attach.component.html',
  styleUrls: ['./add-attach.component.scss'],
})
export class AddAttachComponent implements OnInit {

  private eitResponse: any;//AddEitResponse=new AddEitResponse();
  isUpload: boolean = false;
  inQueue: boolean = false;
  addAttachmentListReq: any;
  attachmentID: number = 0;
  addAttachRequest: any = [];
  fileData: any;
  fileType: any;
  index: any = 1;
  dirPage: any;
  TransactionID: any;
  indexLastObj: any = 0;
  filterAllowedType: any = ['application/pdf', 'image/jpeg', 'image/png', 'text/plain', 'image/jpg', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];


  constructor(public cs: CommonService, public ts: TranslatorService, public modalCtrl: ModalController) {
    this.eitResponse = this.cs.sharedService.getSharedData(AddEitResponse.SHARED_DATA, false);
    this.TransactionID = this.cs.sharedService.getSharedData('TransactionID', false);
    this.indexLastObj = this.cs.sharedService.getSharedData('indexLastObj', false);

    // console.log("this.TransactionID : "+ this.TransactionID);
    this.isUpload = false;
  }

  ngOnInit() { }

  public uploader: FileUploader = new FileUploader({
    allowedMimeType: ['application/pdf', 'image/jpeg', 'image/png', 'text/plain', 'image/jpg', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
    maxFileSize: 10 * 1024 * 1024,
    formatDataFunctionIsAsync: true,
    formatDataFunction: async (item) => {
      return new Promise((resolve, reject) => {
        resolve({
          name: item._file.name,
          length: item._file.size,
          contentType: item._file.type,
          date: new Date()
        });
      });
    }
  });

  public hasBaseDropZoneOver: boolean = false;
  public hasAnotherDropZoneOver: boolean = false;

  public fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }

  public fileOverAnother(e: any): void {
    this.hasAnotherDropZoneOver = e;
  }

  OkBtnModal() {
    let fileCount: number = this.uploader.queue.length;
    if (fileCount > 0) {
      let data: any = this.addAttachRequest;
      // this.viewCtrl.dismiss(data);

      this.modalCtrl.dismiss(data);

    }
    else {
      let msg: string = "";
      msg = this.ts.trPK("general", "noFileSelect");
      this.cs.presentAlert(msg);
      return;
    }
  } // end ok button

  closeBtnModal() {
    // this.viewCtrl.dismiss("cancel");
    this.modalCtrl.dismiss("cancel");

  }

  onFileSelected(input) {

    // this.uploader.onWhenAddingFileFailed = function (item: any, filter: any, options: any){

    if (!(this.filterAllowedType.indexOf(input.target.files[0].type) > -1)) {
      let msg: string = "";
      msg = this.ts.trPK("general", "notSupport");
      this.cs.presentAlert(msg);
      return
    }    // todo: show alert that you tried uploading wrong files

    else {

      const file = input.target.files[0];

      // console.log(file);

      //var encoded = Base64.encode(file); 
      this.getBase64(file).then(
        data => this.pushObject(data, file.name, file.type)
      );

      // }
      // };

    }
  }


  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }


  pushObject(fileData, name, type) {

    // console.log("before push: "+ this.index);
    this.indexLastObj++;
    try {
      let array = name.split('.');
      let attachType: string = array[array.length - 1];

      this.addAttachRequest.push(
        {
          AttachmentID: this.indexLastObj,
          P_FILE_CONTENT_TYPE: attachType,//type.split('/')[1],
          P_FILE_DATA: fileData.split(',')[1],
          P_FILE_NAME: name,//.split('.')[0],
          P_TRANSACTION_ID: this.TransactionID
        })

    } catch (e) {

    }


    //console.log("after push: "+ this.index);
    // return  this.addAttachRequest
  }


  removeFile(objectitem) {

    let objIndex1 = this.uploader.queue.findIndex(item => item == objectitem);
    this.uploader.queue.splice(objIndex1, 1);
    let objIndex = this.addAttachRequest.findIndex(item => item.AttachmentID == objectitem.AttachmentID);
    this.addAttachRequest.splice(objIndex, 1);
    // this.addAttachRequest =this.addAttachRequest.filter(item => item.AttachmentID !== objectitem.AttachmentID); 

  }





}
