import {
  Component,
  OnInit,
  ViewChild,
  ElementRef,
  NgZone
} from '@angular/core';
import { Location } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { MapsAPILoader, MouseEvent } from '@agm/core';
import { Address } from './../../config/services/address';
import { AddressService } from './../../config/address.service';
import { ServiceService } from './../../config/service.service';
import { AuthService } from './../../config/auth.service';
import { NgForm } from '@angular/forms';
import * as firebase from 'firebase';
/* import { google } from '@agm/core/services/google-maps-types'; */

@Component({
  selector: 'app-nearby',
  templateUrl: './nearby.page.html',
  styleUrls: ['./nearby.page.scss']
})
export class NearbyPage implements OnInit {
  latitude: number;
  longitude: number;
  zoom: number;
  address: string;
  private geoCoder;
  addressForm: NgForm;
  addressData = new Address('', '', '', '', true, '', 0, '');
  successState: boolean;
  uid: string;
  type: any;
  loader: boolean;
  @ViewChild('building', { static: false })
  public searchElementRef: ElementRef;

  newCenterLat: number;
  newCenterLng: number;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone,
    public addressService: AddressService,
    public service: ServiceService,
    public authService: AuthService
  ) {
    this.latitude = 0;
    this.longitude = 0;
    this.successState = false;
    this.type = 0;
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.uid = data.uid;
      }
    });

    this.service.get('type').then(data => {
      this.type = data;
    });
  }

  ngOnInit() {
    // load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.Geocoder();
      const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ['address']
      });
      autocomplete.addListener('place_changed', () => {
        this.ngZone.run(() => {
          const place: google.maps.places.PlaceResult = autocomplete.getPlace();
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }
          this.latitude = place.geometry.location.lat();
          this.longitude = place.geometry.location.lng();
          this.newCenterLat = place.geometry.location.lat();
          this.newCenterLng = place.geometry.location.lng();
          console.log(this.latitude, this.longitude);
          this.zoom = 16;
        });
      });
    });
  }
  // google maps zoom level

  private setCurrentLocation() {
    if ('geolocation' in navigator) {
      this.zoom = 16;
      this.getAddress(this.latitude, this.longitude);
      navigator.geolocation.getCurrentPosition(position => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        this.zoom = 16;
        this.getAddress(this.latitude, this.longitude);
      });
    }
  }

  markerDragEnd($event: MouseEvent) {
    console.log($event);
    this.latitude = $event.coords.lat;
    this.longitude = $event.coords.lng;
    this.getAddress(this.latitude, this.longitude);
  }

  getAddress(latitude, longitude) {
    this.geoCoder = new google.maps.Geocoder();
    this.geoCoder.geocode(
      { location: { lat: latitude, lng: longitude } },
      (results, status) => {
        console.log(results);
        console.log(status);
        if (status === 'OK') {
          if (results[0]) {
            this.zoom = 16;
            this.address = results[0].formatted_address;
            console.log(this.address);
          } else {
            console.log('No results found');
          }
        } else {
          console.log('Geocoder failed due to: ' + status);
        }
      }
    );
  }

  mapReady(map) {
    console.log('called');
    map.addListener('dragend', () => {
      console.log(this.searchElementRef.nativeElement.value);
      console.log(this.newCenterLat, this.newCenterLng);
      this.getAddress(this.newCenterLat, this.newCenterLng);
      const This = this;
      setTimeout(() => {
        This.searchElementRef.nativeElement.value = this.address;
      }, 500);

    });
  }
  centerChange(e) {
    console.log('called - 2');
    console.log(e);
    this.newCenterLat = e.lat;
    this.newCenterLng = e.lng;
    // this.getAddress(this.newCenterLat, this.newCenterLng);
  }

  goToPage(path, data = null) {
    this.router.navigateByUrl(path, { queryParams: data });
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  goBack() {
    window.history.back();
  }

  onSubmit(data: any) {
    this.loader = true;
    console.log(data);
    const postData: Address = {
      address: '',
      addressType: data.addressType,
      building: this.searchElementRef.nativeElement.value,
      landmark: data.landmark !== undefined ? data.landmark : '',
      defaultVal: 0,
      uid: this.uid,
      latLng: new firebase.firestore.GeoPoint(this.newCenterLat, this.newCenterLng),
      status: true
    };
    this.addressService.addressCreate(postData);
    this.successState = true;

    setTimeout(() => {
      this.loader = false;
      this.successState = false;
      if (this.authService.regState === false) {
        this.router.navigateByUrl('preference', { queryParams: null });
      } else {
        if (this.addressService.addressState === 1) {
          this.addressService.addressState = 0;
          this.router.navigateByUrl('cart', { replaceUrl: true });
        } else {
          this.goBack();
        }
      }
    }, 3000);
  }
}

interface Marker {
  lat: number;
  lng: number;
  label?: string;
  draggable: boolean;
}
