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

  constructor(
    public photoService: PhotoService,
    private publications: PublicationsService,
    private camera: Camera,
    private toastService: ToastService,
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service
  ) {
    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;
    });
  }


  takePicture() {
    const options: CameraOptions = {
      quality: 90,
      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) => {

     this.capturedImage = 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
    };

  }


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

    }
  }

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

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

}
