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 { MyordersService } from './../../config/myorder.service';
import { NgForm } from '@angular/forms';
import * as firebase from 'firebase';
declare var google: any;

@Component({
  selector: 'app-changeaddress',
  templateUrl: './changeaddress.page.html',
  styleUrls: ['./changeaddress.page.scss']
})
export class ChangeaddressPage 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;
  order: any;
  addressValid: any;
  lat: any;
  lng: any;
  newCenterLat: number;
  newCenterLng: number;
  @ViewChild('building', { static: false })
  public searchElementRef: ElementRef;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone,
    public addressService: AddressService,
    public service: ServiceService,
    public myorder: MyordersService
  ) {
    this.addressValid = false;
    this.successState = false;
    this.lat = '';
    this.lng = '';
    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;
    });
    this.service.get('order').then(val => {
      this.order = val;
    });
  }

  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.zoom = 16;
        });
      });
    });
  }
  // google maps zoom level

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

  mapReady(map) {
    map.addListener('dragend', () => {
      console.log(this.newCenterLat, this.newCenterLng);
      this.getAddress(this.newCenterLat, this.newCenterLng);
    });
  }
  centerChange(e) {
    console.log(e);
    this.newCenterLat = e.lat;
    this.newCenterLng = e.lng;
    this.getAddress(this.newCenterLat, this.newCenterLng);
  }

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

  locationRest() {
    if (this.latitude && this.longitude && this.order) {
      if (this.latitude !== this.lat && this.longitude !== this.lng) {
        this.lat = this.latitude;
        this.lng = this.longitude;
        this.myorder
          .getNearBy(this.latitude, this.longitude, this.order.orderId)
          .then(resp => {
            console.log(resp);
            if (resp) {
              this.addressValid = resp;
            }
          });
      }
    }
    return this.addressValid;
  }

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

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

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

  onSubmit(data: any) {
    console.log();
    const buildAddress = this.searchElementRef.nativeElement.value;
    this.loader = true;
    this.service.get('order').then(val => {
      console.log(val);
      const This = this;
      console.log(
        This.latitude,
        This.longitude,
        val.pickupLocation.O,
        val.pickupLocation.F
      );
      setTimeout(() => {
        // tslint:disable-next-line:max-line-length
        const distanceNew = google.maps.geometry.spherical.computeDistanceBetween(
          new google.maps.LatLng(This.newCenterLat, This.newCenterLng),
          new google.maps.LatLng(val.pickupLocation.O, val.pickupLocation.F)
        );
        const distanceKM = (distanceNew / 1000).toFixed(2);
        if (distanceKM < This.service.distance) {
          console.log(buildAddress);
          const orderId = val.orderId;
          const postData: Address = {
            addressType: data.addressType,
            address: '',
            building: buildAddress,
            landmark: data.landmark !== undefined ? data.landmark : '',
            defaultVal: 0,
            uid: This.uid,
            latLng: new firebase.firestore.GeoPoint(
              This.newCenterLat,
              This.newCenterLng
            ),
            status: true
          };
          console.log(postData, orderId);
          This.addressService.changeAddress(postData, orderId);
          val.deliveryAddress = postData;
          This.service.set('order', val);
          This.successState = true;

          setTimeout(() => {
            This.loader = false;
            This.successState = false;
            This.goBack();
          }, 3000);
        } else {
          This.loader = false;
          This.service.showToast(
            'Does not delivered to choosed location',
            'top',
            'my-error',
            2000
          );
        }
      }, 1000);
    });
  }
}

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