import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams, Platform, LoadingController, PopoverController } from '@ionic/angular';

/* import {Plugins, CameraResultType, CameraSource} from '@capacitor/core'; */
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { PublicationsService } from 'src/app/services/publications.service';
import { Publication } from 'src/app/models/publication';
import { Image } from 'src/app/models/image';
import { PhotoService } from 'src/app/services/photo.service';
//Capacitor

import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ThemePalette } from '@angular/material/core';
import { formatDate } from 'src/plugin/momentG.js'
import { FileLoaderService } from 'src/app/services/file/file-loader.service';
import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service';
import { ThemeService } from 'src/app/services/theme.service';
import { Camera, CameraResultType, CameraSource, Photo } from '@capacitor/camera';

import { Filesystem, Directory } from '@capacitor/filesystem';
import { NgxImageCompressService } from "ngx-image-compress";
import { PreviewerPage } from 'src/app/modals/previewer/previewer.page';
const IMAGE_DIR = 'stored-images';

interface LocalFile {
  name: string;
  path: string;
  data: string;
}
@Component({
  selector: 'app-new-publication',
  templateUrl: './new-publication.page.html',
  styleUrls: ['./new-publication.page.scss'],
})
export class NewPublicationPage implements OnInit {
  images: LocalFile[] = [];

  // date picker
  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public minDate = new Date().toISOString().slice(0, 10)
  public endMinDate = new Date(new Date().getTime() + 15 * 60000);
  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;
  public color: ThemePalette = 'primary';

  Form: FormGroup;
  validateFrom = false

  showLoader: boolean;
  publication: Publication;
  pub: Publication = new Publication();
  folderId: string;
  image: Image = new Image();

  publicationType: string;
  publicationTitle: string;
  imgUrl: any;

  Defaultimage: any = '';

  photo: SafeResourceUrl;

  guestPicture: any;

  capturedImage: any = '';
  capturedImageTitle: any;
  public photos: any[] = [];

  imgResultBeforeCompress: string;
  imgResultAfterCompress: string;
  convertBlobToBase64Worker;

  constructor(
    private modalController: ModalController,
    private popoverController: PopoverController,
    public photoService: PhotoService,
    private navParams: NavParams,
    private publications: PublicationsService,
    private toastService: ToastService,
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service,
    public ThemeService: ThemeService,
    private platform: Platform,
    private loadingCtrl: LoadingController,
    public imageCompress: NgxImageCompressService,
  ) {

    this.publicationType = this.navParams.get('publicationType');
    this.folderId = this.navParams.get('folderId');
    this.publicationTitle = 'Nova Publicação';


    this.convertBlobToBase64Worker = new Worker(new URL('./convertBlobToBase64.worker.js', import.meta.url));

  }

  ngOnInit() {
    this.setTitle();
    console.log(this.folderId);
    Filesystem.mkdir({
      path: IMAGE_DIR,
      directory: Directory.Data,
      recursive: true
    });

    // this.takePicture();
  }

  async takePicture() {

    const capturedImage = await Camera.getPhoto({
      quality: 90,
      // allowEditing: true,
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera
    });

    const response = await fetch(capturedImage.webPath!);
    const blob = await response.blob();

    this.convertBlobToBase64Worker.postMessage(blob);
    this.convertBlobToBase64Worker.onmessage = async (oEvent)=> {
      this.capturedImage = oEvent.data

    }
  }

  imageSize(image) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = 100
    canvas.height = 34
    ctx.drawImage(image, 0, 0, 100, 34);
    document.body.appendChild(canvas);
  }

  convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
    const reader = new FileReader;
    reader.onerror = reject;
    reader.onload = () => {
        resolve(reader.result);
    };
    reader.readAsDataURL(blob);
  });


  async laodPicture() {
    const capturedImage = await Camera.getPhoto({
      resultType: CameraResultType.Uri,
      source: CameraSource.Photos,
      quality: 90,
      width: 1080,
      height: 720,
    });

    const response = await fetch(capturedImage.webPath!);
    const blob = await response.blob();

    this.photos.unshift({
      filepath: "soon...",
      webviewPath: capturedImage.webPath
    });

    this.capturedImage = await this.convertBlobToBase64(blob);
    this.capturedImageTitle = new Date().getTime() + '.jpeg';
  }

  /* laodPicture() {
    const input = this.fileLoaderService.createInput({
      accept: ['image/apng', 'image/jpeg', 'image/png']
    })

    input.onchange = async () => {
      const file = this.fileLoaderService.getFirstFile(input)

      const imageData =  await this.fileToBase64Service.convert(file)
      this.capturedImage = imageData;
      this.capturedImageTitle = file.name

      console.log(this.capturedImage)
    };

  } */



  runValidation() {
    this.validateFrom = true
  }

  injectValidation() {

    this.Form = new FormGroup({
      Subject: new FormControl(this.pub.Title, [
        //Validators.required,
        // Validators.minLength(4)
      ]),
      capturedImage: new FormControl(this.capturedImage, [

      ]),
      Message: new FormControl(this.pub.Message, [
        // Validators.required
        Validators.maxLength(1000)

      ])
    })
  }

  async save() {

    this.injectValidation()
    this.runValidation()

    if (this.Form.invalid) return false



    if (this.publicationType == '3') {
      console.log(this.navParams.get('publication'));

      if (this.capturedImage != '') {
        this.publication = {
          DateIndex: this.publication.DateIndex,
          DocumentId: this.publication.DocumentId,
          ProcessId: this.publication.ProcessId,
          Title: this.pub.Title,
          Message: this.pub.Message,
          DatePublication: this.publication.DatePublication,
          OriginalFileName: this.capturedImageTitle,
          FileBase64: this.capturedImage,
          FileExtension: 'jpeg',
        }

        const loader = this.toastService.loading()

        try {
          console.log(this.publication);

          await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise()
          this.toastService.successMessage("Publicação editada")

          this.close();
        } catch (error) {
          this.toastService.badRequest("Publicação não editada")
        } finally {
          loader.remove()
        }

      }
      else if (!this.publication.OriginalFileName) {

        this.publication = {
          DateIndex: this.publication.DateIndex,
          DocumentId: this.publication.DocumentId,
          ProcessId: this.publication.ProcessId,
          Title: this.pub.Title,
          Message: this.pub.Message,
          DatePublication: this.publication.DatePublication,
          // OriginalFileName: this.publication.OriginalFileName,
          // FileBase64: this.publication.FileBase64,
          // FileExtension: 'jpeg',
        }
        /* console.log('Edit - keep image');
        console.log(this.publication); */

        const loader = this.toastService.loading()

        try {
          console.log(this.publication);
          await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise()
          this.toastService.successMessage("Publicação criado")

          this.close();
        } catch (error) {
          this.toastService.badRequest("Publicação não criado")
        } finally {
          loader.remove()
        }

      } else {
        this.publication = {
          DateIndex: this.publication.DateIndex,
          DocumentId: this.publication.DocumentId,
          ProcessId: this.publication.ProcessId,
          Title: this.pub.Title,
          Message: this.pub.Message,
          DatePublication: this.publication.DatePublication,
          OriginalFileName: this.capturedImageTitle,
          FileBase64: this.capturedImage,
          FileExtension: 'jpeg',
        }

        console.log('Edit change image');
        console.log(this.publication);
        const loader = this.toastService.loading()

        try {
          await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise()
          this.toastService.successMessage("Publicação criado")

          this.close();
        } catch (error) {
          this.toastService.badRequest("Publicação não criado")
        } finally {
          loader.remove()
        }

      }
    }
    else {

      const date = formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')
      console.log(date);
      console.log(this.folderId);


      this.publication = {
        DateIndex: date,
        DocumentId: null,
        ProcessId: this.folderId,
        Title: this.pub.Title,
        Message: this.pub.Message,
        DatePublication: date,
        OriginalFileName: this.capturedImageTitle,
        FileBase64: this.capturedImage,
        FileExtension: 'jpeg',
      }

      const loader = this.toastService.loading()

      try {
        console.log(this.publication);
        await this.publications.CreatePublication(this.folderId, this.publication).toPromise();
        this.close();
        this.toastService.successMessage("Publicação criado")


        this.close();
      } catch (error) {
        this.toastService.badRequest("Publicação não criado")
      } finally {
        loader.remove()
      }

    }
  }


  close() {
    this.modalController.dismiss().then(() => {
      this.showLoader = true;
    });
  }

  clear() {
    this.capturedImage = '';
  }

  setTitle() {
    if (this.publicationType == '1') {
      this.publicationTitle = 'Nova Publicação Rápida';
    }
    else if (this.publicationType == '2') {
      this.publicationTitle = 'Nova Publicação';
    }
    else if (this.publicationType == '3') {
      this.publicationTitle = 'Editar Publicação';
      this.pub = this.navParams.get('publication');

      console.log(this.pub, 'pub')
    }
  }

  /* async openGallery() {
    const modal = await this.modalController.create({
      component: GalleryPage,
      componentProps:{
      },
      cssClass: 'new-publication',
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss();
  } */

  /* async takePicture(){
   const image = await Plugins.Camera.getPhoto({
     quality: 100,
     allowEditing: false,
     resultType: CameraResultType.DataUrl,
     source: CameraSource.Camera
   });
   console.log(image);

   this.photo = this.sanitizer.bypassSecurityTrustResourceUrl(image && (image.dataUrl));
 } */

  async selectImage() {
    const image = await Camera.getPhoto({
      quality: 90,
      allowEditing: false,
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera // Camera, Photos or Prompt!
    });
    if (image) {
      this.saveImage(image)
    }
  }



  // Create a new file from a capture image
  async saveImage(photo: Photo) {
    const base64Data = await this.readAsBase64(photo);

    const fileName = new Date().getTime() + '.jpeg';
    const savedFile = await Filesystem.writeFile({
      path: `${IMAGE_DIR}/${fileName}`,
      data: base64Data,
      directory: Directory.Data
    });

    //this.loadFiles(fileName);
    this.loadFileData(fileName);
  }

  private async readAsBase64(photo: Photo) {
    if (this.platform.is('hybrid')) {
      const file = await Filesystem.readFile({
        path: photo.path
      });

      return file.data;
    }
    else {
      // Fetch the photo, read as a blob, then convert to base64 format
      const response = await fetch(photo.webPath);
      const blob = await response.blob();

      return await this.convertBlobToBase64(blob) as string;
    }
  }

  async loadFiles(fileName) {
    this.images = [];

    const loading = await this.loadingCtrl.create({
      message: 'Loading data...',
    });
    await loading.present();

    /* Filesystem.readdir({
      path: `${IMAGE_DIR}/${fileName}`,
      directory: Directory.Data,
    }).then(result => {
      console.log('ALL RESULTS', result.files)
      let lastphoto = result.files[result.files.length - 1]
      this.loadFileData(lastphoto);
    },
      async (err) => {
        console.log('ERROR FILE DOSENT EXIST', err)
        // Folder does not yet exists!
        await Filesystem.mkdir({
          path: IMAGE_DIR,
          directory: Directory.Data,
          recursive: true
        });
      }
    ).then(_ => {
      loading.dismiss();
    }); */
  }

  async loadFileData(fileName: string) {
    console.log('ALL PHOTOT FILE', fileName)

    const loading = await this.loadingCtrl.create({
      message: 'Loading data...',
    });
    await loading.present();

    const filePath = `${IMAGE_DIR}/${fileName}`;

    const readFile = await Filesystem.readFile({
      path: filePath,
      directory: Directory.Data,
    });

    this.images.push({
      name: fileName,
      path: filePath,
      data: `data:image/jpeg;base64,${readFile.data}`,
    });

    console.log('ALL IMAGE', this.images)

    this.capturedImage = this.images[0].data

    this.compressFile();

    loading.dismiss();

  }

  /*   compressImage() {
      let image = this.capturedImage;
      this.imageCompress.compressFile(image, orientation, 50, 50,).then(() => {

        this.imgResultBeforeCompress = image;
        console.log('Size in bytes was:', this.imageCompress.byteCount(image));

        this.imageCompress.compressFile(image, orientation, 50, 50).then(
          result => {
            this.imgResultAfterCompress = result;
            console.log('Size in bytes is now:', this.imageCompress.byteCount(result));
          }
        );
      })
    } */

  compressFile() {

    //this.imgResultBeforeCompress = image;s
    this.imageCompress.getOrientation(this.capturedImage).then((orientation) => {
      console.log('Size in bytes was:', this.imageCompress.byteCount(this.capturedImage));
      this.imageCompress.compressFile(this.capturedImage, orientation, 90, 90).then(
        result => {
          this.capturedImage = result;
          console.log('Size in bytes is now:', this.imageCompress.byteCount(result));
        }
      );

    });
  }



}
