import { Injectable } from '@angular/core';
import { FileLoaderService } from '../file/file-loader.service';
import { FileToBase64Service } from '../file/file-to-base64.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

import { ChatService } from '../chat.service';
import { ModalController, Platform,LoadingController } from '@ionic/angular';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { ProcessesService } from '../processes.service';
import { ToastService } from '../toast.service';
import { Camera,  CameraResultType, CameraSource, Photo} from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

const IMAGE_DIR = 'stored-images';


interface LocalFile {
  name: string;
  path: string;
  data: string;
}

@Injectable({
  providedIn: 'root'
})
export class FileService {

  images: LocalFile[] = [];
  capturedImage:any;
  capturedImageTitle:any;
  documents:SearchList[] = [];
  showLoader: boolean;

  files: Set<File>;
  photos: any[] = [];
  idroom: any;

  headers: HttpHeaders;

  constructor(
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service,
    private iab: InAppBrowser,
    private chatService: ChatService,
    private modalController: ModalController,
    private processesService: ProcessesService,
    private toastService: ToastService,
    private platform: Platform,
    private loadingCtrl: LoadingController,
    private http: HttpClient,
  ) {
    this.headers = new HttpHeaders();
  }

  uploadFile(formData:any){

    //const geturl = environment.apiURL + 'Tasks/DelegateTask';
    const geturl = environment.apiURL + 'lakefs/UploadFiles';

    let options = {
      headers: this.headers
    };

    return this.http.post(`${geturl}`, formData, options);
  }

  getFile(guid:any){
    const geturl = environment.apiURL + 'lakefs/StreamFile';
    let params = new HttpParams();

    params = params.set("path", guid);

    this.headers = this.headers.set('responseType', 'blob');
    this.headers = this.headers.set('Content-Type', 'application/octet-stream');

    let options = {
      headers: this.headers,
      params: params
    };
    return this.http.get<any>(`${geturl}`, options);
  }

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

    let data = {
      image:this.capturedImage,
      name: this.capturedImageTitle
    }

    return data;
  }

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

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

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

      console.log(file);

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

      let data = {
        image:this.capturedImage,
        name: this.capturedImageTitle
      }

      return data;
    };
  }

  //new method1
  async saveImage(photo: Photo, roomid: any) {
    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(roomid);
  }

  //new method 2
  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;
    }
  }

  //new method 3
  async loadFiles(roomid) {
    this.images = [];

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

    Filesystem.readdir({
      path: IMAGE_DIR,
      directory: Directory.Data,
    }).then(result => {
      console.log('ALL RESULTS', result.files[0])
      let lastphoto = result.files[result.files.length - 1]
      this.loadFileData(lastphoto,roomid);
    },
      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();
    });
  }

  //new method 4
  async loadFileData(fileName: string, roomid: any) {
    console.log('ALL PHOTOT FILE', fileName)
    // for (let f of fileNames) {
    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.capturedImageTitle = new Date().getTime() + '.jpeg';

    let body = {
      "message":
      {
        "rid": roomid,
        "msg": "",
        "attachments": [{
          "title": this.capturedImageTitle,
          "title_link_download": false,
          "image_url": this.capturedImage,
        }]
      }
    }
    console.log('BODY TAKE PICTURE CHAT', body)
    const loader = this.toastService.loading();
    this.chatService.sendMessage(body).subscribe(res=> {
      console.log(res);
      loader.remove();
    },(error) => {
      loader.remove();
      this.toastService.badRequest("Não foi possível adicionar a fotografia!");
    });
  }



  async addCameraPictureToChat(roomId){

    const image = await Camera.getPhoto({
      quality: 50,
      allowEditing: false,
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera // Camera, Photos or Prompt!
    });

    if (image) {
      await this.saveImage(image,roomId)
    }

      //this.capturedImage = this.capturedImage;


  }

  async addPictureToChatMobile(roomId) {

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

    });

    if (capturedImage) {
      await this.saveImage(capturedImage,roomId)
    }


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

      //const loader = this.toastService.loading();

      let body = {
        "message":
        {
          "rid": roomId,
          "msg": "",
          "attachments": [{
            //"title": this.capturedImageTitle ,
            //"text": "description",
            "title_link_download": false,
            "image_url": this.capturedImage,
          }]
        }
      }
      this.chatService.sendMessage(body).subscribe(res=> {
        //loader.remove();
        //console.log(res);
      },(error) => {
        //loader.remove();
      });
 */  }

  addPictureToChat(roomId) {

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


    setInterval(()=>{
      console.log(input.value)
    }, 550)


    input.onchange = async () => {

      //alert('Onchange AQUI')

      const file = this.fileLoaderService.getFirstFile(input)

      console.log(file);


      const formData = new FormData();
      formData.append("blobFile", file);
      let guid: any = await this.uploadFile(formData).toPromise()
      console.log(guid.path);

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

      let body = {
        "message":
        {
          "rid": roomId,
          "msg": "",
          "attachments": [{
            //"title": this.capturedImageTitle ,
            //"text": "description",
            "title_link_download": false,
            //"image_url": this.capturedImage,
          }],
          "file":{
            "type": "application/img",
            "guid": guid.path,
          }
        }
      }

      console.log('SELECT PICTURE GALLERY', body)
      console.log(this.capturedImage)

      this.chatService.sendMessage(body).subscribe(res=> {

        //console.log(res);
      },(error) => {
      });
      //console.log(this.capturedImage)
    };
  }

  addDocumentToChat(roomId:string) {
    const input = this.fileLoaderService.createInput({
      accept: ['.doc', '.docx', '.pdf']
    })

    input.onchange = async () => {
      const loader = this.toastService.loading();
      const file = this.fileLoaderService.getFirstFile(input)

      console.log(file);

      const formData = new FormData();
      formData.append('file', file, file.name);

      this.chatService.uploadFile(formData, roomId).subscribe(res=> {
        console.log(res);
        loader.remove();
      },(error) => {
        loader.remove();
      });
      //console.log(this.capturedImage)
    };
  }

  async addDocGestaoDocumentalToChat(roomId:string){
    const modal = await this.modalController.create({
      component: SearchPage,
      cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
      componentProps: {
        type: 'AccoesPresidenciais & ArquivoDespachoElect',
        select: true,
        showSearchInput: true,
      }
    });
    await modal.present();
    modal.onDidDismiss().then(async res=>{
      const data = res.data;

      if(data.selected){
        const loader = this.toastService.loading();

        this.documents.push(data.selected);
        console.log(res.data.selected);
        console.log(res.data.selected.Id);
        console.log(res.data.selected.ApplicationType);

        let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
        let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
        console.log(url_no_options);

        let body = {
          "message":
          {
            "rid": roomId,
            "msg": "",
            "attachments": [{
              "title": res.data.selected.Assunto,
              "description": res.data.selected.DocTypeDesc,
              "title_link": url_no_options,
              "title_link_download": true,
              //"thumb_url": "assets/images/webtrix-logo.png",
              "message_link": url_no_options,
              "type": "webtrix"
            }],
            "file":{
              "name": res.data.selected.Assunto,
              "type": "application/webtrix",
              "ApplicationId": res.data.selected.ApplicationType,
              "DocId": res.data.selected.Id,
              "Assunto": res.data.selected.Assunto,
            }
          }
        }
        this.chatService.sendMessage(body).subscribe(res=> {
          loader.remove();
          console.log(res);
        },(error) => {
          loader.remove();
        });
        loader.remove();
      }
    });
  }

  viewDocumentByUrl(url) {
    const browser = this.iab.create(url,"_parent");
    browser.show();
  }
}
