import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ActionSheetController,Events, NavController } from '@ionic/angular';
import {CameraOptions,Camera,PictureSourceType} from '@ionic-native/Camera/ngx';
// import { FileChooser } from '@ionic-native/file-chooser';
import { FilePath } from "@ionic-native/file-path/ngx";
import { File } from "@ionic-native/file/ngx";
import { TranslatorService } from '../../services/translator/translator.service';
import { Base64 } from "@ionic-native/base64/ngx";
import { DevicePermissionsService } from '../../services/device-permissions/device-permissions.service';
// import { Chooser } from '@ionic-native/chooser';

@Component({
  selector: 'app-file-uploder-profile',
  templateUrl: './file-uploder-profile.component.html',
  styleUrls: ['./file-uploder-profile.component.scss'],
})
export class FileUploderProfileComponent implements OnInit {
  
  @Input() multiupload = false;
  @Input() attachmentname = 'attachment-loader';
  public attachmentData: string;
  @Input() maxFileSize = 10 * 1024 * 1024;
  @Output() fileSelected = new EventEmitter();
  @Output() onimgLoad = new EventEmitter();
  public image: string;
  public attachmentImg = 'assets/icon/attachment.png';
  public deleteImg = 'assets/icon/delete.png';
  public defultProfile = '../../../../assets/imgs/profile.png';
  public selectedImage:any;
  public nativePath: any;
  public errorMsg:any;
  public allowdType: any = ["jpg", "jpeg", "png"];
  camera: boolean

  constructor( 
    public cameraController:Camera,
    public actionSheetCtrl:ActionSheetController,
    public event:Events,
    public nav: NavController,
    private filePath: FilePath,
    // public FileChooser:FileChooser,
    private file: File,
    public ts: TranslatorService,
    public base64:Base64,
    private permissions: DevicePermissionsService

    // private chooser: Chooser


    ) { }

  ngOnInit() {

  }

  @Input() set src(src: string) {
    this.image = src;
  }
  get src(): string {
    return this.image;
  }

  //open the presentsheet
  //selected attach
  //need convert 
  //insert or display

  private permissionsToOpenCamera() {
      this.permissions.requestCameraAutherization().then(granted => {
        this.camera = granted as boolean;
        if (this.camera) {
          this.openFile();
        }
      }
      );
  }

  
  async openFile(){
    const actionSheet = await this.actionSheetCtrl.create({
      header: 'Change Profile Photo',
       buttons: [{
      //   text: 'Delete Current Image',
      //   role: 'destructive',
      //   icon: 'trash',
      //   handler: () => {
      //     console.log('Delete clicked');
      //     this.deleteCurrent();
      //   }
      // },{
        text: 'Take Photo',
        icon: 'camera',
        handler: () => {
          console.log('Take Photo');
          this.takePicture(this.cameraController.PictureSourceType.CAMERA);

        }
      }, {
         
        text: 'Choose from Library',
       icon: 'images',
        handler: () => {
          console.log('Favorite clicked');
          this.takePicture(this.cameraController.PictureSourceType.PHOTOLIBRARY);

        }
      }, {
        text: 'Cancel',
        icon: 'close',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }

  public takePicture(sourceType: PictureSourceType) {
    console.log("sourceType: "+sourceType);
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.cameraController.DestinationType.DATA_URL,
      encodingType: this.cameraController.EncodingType.JPEG,
      sourceType: sourceType,
      correctOrientation:true,
      targetWidth: 512,
      targetHeight: 512
    };


      this.cameraController.getPicture(options).then(imageData => {
        const data = "data:image/jpeg;base64," + imageData;
        this.event.publish('Image', {message:"hello"});
        this.selectedImage = "data:image/jpeg;base64, " + imageData;
        this.onimgLoad.emit(this.selectedImage);
    });

  }
  
  public deleteCurrent(){
    // send empty image
    //this.onimgLoad.emit("");
    console.log("deleteCurrent");
    this.encodeFiles(this.defultProfile);

  }
  
  readFile(fileUrl: any) {
    this.filePath.resolveNativePath(fileUrl).then(filePathResult => {
      this.nativePath = filePathResult;
      this.file.resolveLocalFilesystemUrl(this.nativePath).then(entry => {
        entry.getMetadata(metadata => {
          if (metadata.size <= this.maxFileSize) {
            this.errorMsg = null;
            this.encodeFiles(entry);
          } else {
            this.errorMsg = this.ts.trPK("general", "large-file");
          }
        });
      });
    });
  }

  encodeFiles(entry) {
  alert("encodeFiles")
    this.base64.encodeFile(entry).then(
      (base64File: string) => {

        // const type = this.nativePath.substr(
        //   this.nativePath.lastIndexOf(".") + 1
        // );

        alert("base64File 1" + base64File);

        // if (this.allowdType.includes(type.toLowerCase())) {
        // } else {
        //   this.attachmentData = null;
        //   this.errorMsg = this.ts.trPK("general", "not-supported");
        // }
      },
      err => {
        console.log(err);
      }
    );
  }
  

}
