import { Component, OnInit } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { Camera, CameraOptions, PictureSourceType } from '@ionic-native/Camera/ngx';
import { File, FileEntry } from '@ionic-native/File/ngx';
import { WebView } from '@ionic-native/ionic-webview/ngx';
import { FilePath } from '@ionic-native/file-path/ngx';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AlertService } from 'src/app/services/alert.service';
import { DomSanitizer } from '@angular/platform-browser';

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

  private loading;

  storedPhoto;
  resolvedImage = null;
  safeImage = null;
  contract_id = null;
  description: string;
  myPosition: any = {};

  constructor(
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private navCtrl: NavController,
    private loadingCtrl: LoadingController,
    private activatedRoute: ActivatedRoute,
    private locaccuracy: LocationAccuracy,
    private geolocation: Geolocation,
    private camera: Camera,
    private file: File,
    private webview: WebView,
    private filePath: FilePath,
    private sanitizer: DomSanitizer
  ) { }

  ngOnInit() {
    this.contract_id = this.activatedRoute.snapshot.paramMap.get('contract_id');
    this.getCurrentLocation();
  }

  getCurrentLocation() {
        this.locaccuracy.request(this.locaccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => {
          this.geolocation.getCurrentPosition({ maximumAge: 20000, timeout: 30000, enableHighAccuracy: true }).then((resp) => {
            console.log(resp);
            this.myPosition = {
              latitude: resp.coords.latitude,
              longitude: resp.coords.longitude
            }
          }).catch((error) => {
            console.log('Error al obtener localización: ' + error);
          });
        }, (error) => {
          console.log(error);
        });
  }

  openCamera(){
    const options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.FILE_URI,
    encodingType: this.camera.EncodingType.JPEG,
   }

    this.camera.getPicture(options).then((tempImage) => {
      const tempFilename = tempImage.substr(tempImage.lastIndexOf('/') + 1);
      const tempBaseFilesystemPath = tempImage.substr(0, tempImage.lastIndexOf('/') + 1);
      const newBaseFilesystemPath = this.file.dataDirectory;

      this.file.copyFile(tempBaseFilesystemPath, tempFilename, newBaseFilesystemPath, tempFilename);

      this.storedPhoto = newBaseFilesystemPath + tempFilename;
      //this.resolvedImage = (this.webview.convertFileSrc(this.storedPhoto)).replace('http://localhost/_app_file_', '');
      this.resolvedImage = this.webview.convertFileSrc(this.storedPhoto);
      this.safeImage = this.sanitizer.bypassSecurityTrustUrl(this.resolvedImage);
      this.alertService.presentToast(this.resolvedImage);
    }, (err) => {
       // Handle error
       this.alertService.presentToast("error: " + err)
    });
  }

  send() {
    this.ichambaService.noHomeConfirm(this.contract_id, this.myPosition.latitude, this.myPosition.longitude, this.description).subscribe(
      data => {
        this.alertService.presentToast(data['message']);
        this.navCtrl.navigateRoot('/dashboard');
      }, error => {
        this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
      });
  }

  startUpload() {
    this.file.resolveLocalFilesystemUrl(this.storedPhoto)
        .then(entry => {
            ( < FileEntry > entry).file(file => this.readFile(file))
        })
        .catch(err => {
            this.alertService.presentToast("error: " + err)
        });
  }

  readFile(file: any) {
      const reader = new FileReader();
      reader.onload = () => {
          const formData = new FormData();
          const imgBlob = new Blob([reader.result], {
              type: file.type
          });
          formData.append('file', imgBlob, file.name);
          //this.uploadImageData(formData);
      };
      reader.readAsArrayBuffer(file);
      this.alertService.presentToast("Todo bien hasta ahora");
  }
}
