import { FormGroup, FormControl } from '@angular/forms';
import { GeolocationResponse } from './../../../../../interfaces/location-response.interface';
import { lastValueFrom } from 'rxjs';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { LoginPlace } from './../../../../../interfaces/user-connections.interface';
import { GeolocationService } from 'src/app/services/geolocation.service';
import { Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-map-viewer',
  templateUrl: './map-viewer.component.html',
  styleUrls: ['./map-viewer.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MapViewerComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  locationForm: FormGroup;
  deviceForm: FormGroup;
  isLocation: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) private data: any
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.isLocation = true;

    this.locationForm = new FormGroup({
      latitude: new FormControl({value: '', disabled: false}),
      longitude: new FormControl({value: '', disabled: false}),
      accuracy: new FormControl({value: '', disabled: false}),
      city: new FormControl({value: '', disabled: false}),
      state: new FormControl({value: '', disabled: false}),
      country: new FormControl({value: '', disabled: false}),
    });

    this.deviceForm = new FormGroup({
      device: new FormControl({value: '', disabled: false}),
      os: new FormControl({value: '', disabled: false}),
      vos: new FormControl({value: '', disabled: false}),
      navigator: new FormControl({value: '', disabled: false}),
    });
  }

  ngOnInit(): void {
    this.isLocation = this.data.isLocation;
    if(this.isLocation){
      let locationStr = this.data.location;
      let locationObj = JSON.parse(locationStr);
  
      this.locationForm.patchValue({
        latitude: locationObj.lati,
        longitude: locationObj.long,
        accuracy: locationObj.prec,
        city: locationObj.ciud == null ? '-' : locationObj.ciud!,
        state: locationObj.esta,
        country: locationObj.pais,
      });
    }else{
      let deviceStr = this.data.deviceInfo;
      let deviceObj = JSON.parse(deviceStr);

      this.deviceForm.patchValue({
        device: deviceObj.device,
        os: deviceObj.os,
        vos: deviceObj.vos,
        navigator: deviceObj.navigator,
      });
    }
  }

  formatAccuracy(accuracy: number): string{
    if(accuracy > 1000){
      return `${(accuracy / 1000).toFixed(2)} km`
    }else{
      return `${accuracy.toFixed(2)} m`
    }
  }
}
