import { Directive, ElementRef, EventEmitter, NgZone, OnInit, Output } from '@angular/core';

declare var google: any;

@Directive({
    selector: '[appGooglePlacesAutocomplete]'
})
export class GooglePlacesAutocompleteDirective implements OnInit {

    @Output() readonly addressSelected: EventEmitter<any> = new EventEmitter();

    private readonly element: HTMLInputElement;

    static getFormattedAddress(place): any {
        const googleLocation: any = {};
        googleLocation.lat = place.geometry.location.lat();
        googleLocation.lng = place.geometry.location.lng();
        googleLocation.address = place.name;
        googleLocation.formatted = place.formatted_address;
        // for (const i in place.address_components) {
        //     if (place.address_components.hasOwnProperty(i)) {
        //         const item = place.address_components[i];
        //         googleLocation.address = place.formatted_address;
                // if (item.types.indexOf('administrative_area_level_1') > -1) {
                //   googleLocation.city = item.long_name;
                // } else if (item.types.indexOf('administrative_area_level_2') > -1) {
                //   googleLocation.town_area = item.long_name;
                // } else if (item.types.indexOf('administrative_area_level_3') > -1) {
                //   if (!googleLocation.town_area) {
                //     googleLocation.town_area = item.long_name;
                //   }
                // } else if (item.types.indexOf('country') > -1) {
                //   googleLocation.country = item.long_name;
                // } else if (item.types.indexOf('postal_code') > -1) {
                //   googleLocation.zipcode = item.short_name;
                // } else if (item.types.indexOf('route') > -1) {
                //   googleLocation.street = item.long_name;
                // } else if (item.types.indexOf('route') > -1) {
                //   googleLocation.street = item.long_name;
                // } else if (item.types.indexOf('street_number') > -1) {
                //   googleLocation.building_no = item.long_name;
                // }
            // }
        // }

        return googleLocation;
    }

    constructor(
        private elRef: ElementRef,
        private zn: NgZone
        ) {
        this.element = elRef.nativeElement;
    }

    ngOnInit(): void {
        const autocomplete = new google.maps.places.Autocomplete(this.element);
        google.maps.event.addListener(autocomplete, 'place_changed', () => {
            this.zn.run(() => {
                this.addressSelected.emit(GooglePlacesAutocompleteDirective.getFormattedAddress(autocomplete.getPlace()));
            });
        });
    }

}
