import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams } 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

//Cordova
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
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';

@Component({
  selector: 'app-new-publication',
  templateUrl: './new-publication.page.html',
  styleUrls: ['./new-publication.page.scss'],
})
export class NewPublicationPage implements OnInit {

  // 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;

  constructor(
    private modalController: ModalController,
    public photoService: PhotoService,
    private navParams: NavParams,
    private publications: PublicationsService,
    private camera: Camera,
    private toastService: ToastService,
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service
    ) {
      
      this.publicationType = this.navParams.get('publicationType');
      this.folderId = this.navParams.get('folderId');
      this.publicationTitle = 'Nova Publicação';
    }

  ngOnInit() {
    this.setTitle();
    this.clear();
    // this.takePicture();
  }

  takePicture() {
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 720,
      targetHeight: 720,
    }

    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64 (DATA_URL): m
      //let base64Image = 'data:image/jpeg;base64,' + imageData;
      
      this.capturedImage = 'data:image/png;base64,'+imageData;
      this.capturedImageTitle = new Date().getTime() + '.jpeg';
    }, (err) => {
      /* console.log(err); */
    });
  }


  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)
    };

  }

  getPicture() {
    const options: CameraOptions = {
      quality: 90,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 720,
      targetHeight: 720,
    }

    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64 (DATA_URL):
      let base64Image = 'data:image/jpeg;base64,' + imageData;
      this.capturedImage = imageData;
      this.capturedImageTitle = new Date().getTime() + '.jpeg';
    }, (err) => {
      /* console.log(err); */
    });
  }

  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 criado")

          this.close();
        } catch (error) {
          this.toastService.badRequest("Publicação não criado")
        } 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)

      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));
  } */

}