import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { 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';
import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
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';
@Component({
  selector: 'app-new-publication',
  templateUrl: './new-publication.page.html',
  styleUrls: ['./new-publication.page.scss'],
})
export class NewPublicationPage implements OnInit {
  showLoader: boolean;
  pub: Publication = new Publication();
  image: Image = new Image();

  publicationTitle:string;
  imgUrl:any;

  Defaultimage:any = '';

  Form: FormGroup;
  validateFrom = false

  photo: SafeResourceUrl;

  publication: Publication = new Publication();

  @Input() publicationType: string;
  @Input() folderId: string;
  @Input() publicationId:string;
  @Output() closeDesktopComponent =  new EventEmitter<any>();
  @Output() openPublicationDetails = new EventEmitter<any>();
  @Output() goBackToViewPublications = new EventEmitter<any>();
  @Output()  goBacktoPublicationDetails = new EventEmitter<any>();

  guestPicture:any;

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

  constructor(
    public photoService: PhotoService,
    private publications: PublicationsService,
    private toastService: ToastService,
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service,
    public ThemeService: ThemeService
  ) {
    this.publicationTitle = 'Nova Publicação';
  }

  ngOnInit() {
    if(this.publicationType == '3'){
      this.getPublicationDetail();
    }
    this.setTitle();
    //this.clear();
    //this.takePicture();
  }

  getPublicationDetail() {
    this.showLoader = true;
    //console.log(this.publicationId);
    /* console.log(this.folderId); */
    this.publications.GetPublicationById(this.publicationId).subscribe( res =>{
      //console.log(res);
      /* this.publication = res; */
      this.publication = {
        DateIndex: res.DateIndex,
        DocumentId: res.DocumentId,
        ProcessId:res.ProcessId,
        Title:res.Title,
        Message: res.Message,
        DatePublication: res.DatePublication,
        FileBase64: "data:image/jpg;base64," + res.FileBase64,
        OriginalFileName: res.OriginalFileName,
        FileExtension: 'jpeg',
      }
      this.pub = this.publication;
      this.showLoader = false;
    });
  }


  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.photos.unshift({
        filepath: "soon...",
        webviewPath: capturedImage.webPath
      });
      this.capturedImage = await this.convertBlobToBase64(blob);
      this.capturedImageTitle = new Date().getTime() + '.jpeg';
      //console.log(this.capturedImage);
    }

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


  runValidation() {
    this.validateFrom  = true
  }

  injectValidation() {

    this.Form = new FormGroup({
      Subject: new FormControl(this.pub.Title, [
        // Validators.required,
        // Validators.minLength(4)
      ]),
      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') {

      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',
        }

        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()

          this.goBack();
        } catch (error) {
          this.toastService._badRequest()
        }     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.capturedImageTitle,
          // OriginalFileName: this.publication.OriginalFileName,
          // FileBase64: this.publication.FileBase64,
          // 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()

          this.goBack();
        } catch (error) {
          this.toastService._badRequest()
        }     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()

          this.goBack();
        } catch (error) {
          this.toastService._badRequest()
        }     finally {
          loader.remove()
        }

      }
    }
    else {

      let time =  new Date()
      this.publication = {
        DateIndex: time,
        DocumentId: null,
        ProcessId:this.folderId,
        Title: this.pub.Title,
        Message: this.pub.Message,
        DatePublication: time,
        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.toastService._successMessage()

        this.goBackToViewPublications.emit();
      } catch (error) {
        this.toastService._badRequest()
      }     finally {
        loader.remove()
      }

    }
  }

  close(){
    this.goBack();
  }

  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.publication;
    }
  }

  async goBack(){

    if(this.publicationType == '2'){
      this.goBackToViewPublications.emit();
    } else {
      this.goBackToViewPublications.emit();
      //this.goBacktoPublicationDetails.emit();
    }

  }

}
