import { Component, OnInit } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { Geolocation } from '@capacitor/geolocation';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
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'],
  standalone: false
})
export class NohomePage implements OnInit {

  private loading: any;

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

  constructor(
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private navCtrl: NavController,
    private loadingCtrl: LoadingController,
    private activatedRoute: ActivatedRoute,
    private sanitizer: DomSanitizer
  ) { }

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

  async getCurrentLocation() {
    try {
      // Request permissions first
      const permissionStatus = await Geolocation.checkPermissions();
      if (permissionStatus.location !== 'granted') {
        await Geolocation.requestPermissions();
      }

      const position = await Geolocation.getCurrentPosition({
        enableHighAccuracy: true,
        timeout: 30000
      });

      console.log(position);
      this.myPosition = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude
      };
    } catch (error) {
      console.log('Error al obtener localización: ' + error);
    }
  }

  async openCamera() {
    try {
      const image = await Camera.getPhoto({
        quality: 100,
        resultType: CameraResultType.Uri,
        source: CameraSource.Camera
      });

      // image.webPath will contain a path that can be set as an image src
      this.resolvedImage = image.webPath;
      this.safeImage = this.sanitizer.bypassSecurityTrustUrl(this.resolvedImage || '');
      this.storedPhoto = image.path;
      this.alertService.presentToast(this.resolvedImage || 'Image captured');
    } catch (err) {
      this.alertService.presentToast("error: " + err);
    }
  }

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

  async startUpload() {
    try {
      if (!this.storedPhoto) {
        this.alertService.presentToast("No hay foto para subir");
        return;
      }

      // Read the file as base64
      const contents = await Filesystem.readFile({
        path: this.storedPhoto
      });

      // Convert base64 to Blob
      const byteCharacters = atob(contents.data as string);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'image/jpeg' });

      const formData = new FormData();
      formData.append('file', blob, 'photo.jpg');
      // this.uploadImageData(formData);

      this.alertService.presentToast("Todo bien hasta ahora");
    } catch (err) {
      this.alertService.presentToast("error: " + err);
    }
  }
}
