// Add flexibility to template directive
var template = '<div class="item ion-place-tools-autocomplete">' + '<input type="text" autocomplete="off" ng-model="searchQuery">' + '<div class="ion-place-tools-autocomplete-dropdown" ng-if="dropDownActive">' + '<ion-list>' + '<ion-item ng-repeat="location in locations track by $index" ng-click="selectLocation(location)">' + '{{location.description}}' + '</ion-item>' + '</ion-list>' + '</div>' + '</div>';
angular.module('ion-place-tools', []).service('LocationService', function($q) {
    var autocompleteService = new google.maps.places.AutocompleteService();
    var detailsService = new google.maps.places.PlacesService(document.createElement("input"));
    return {
        searchAddress: function(input) {
            var deferred = $q.defer();
            autocompleteService.getPlacePredictions({
                input: input
            }, function(result, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    // console.log(status);
                    deferred.resolve(result);
                } else {
                    deferred.reject(status)
                }
            });
            return deferred.promise;
        },
        getDetails: function(placeId) {
            var deferred = $q.defer();
            detailsService.getDetails({
                placeId: placeId
            }, function(result) {
                deferred.resolve(result);
            });
            return deferred.promise;
        }
    };
}).directive('ionGooglePlace', function($ionicTemplateLoader, $ionicPlatform, $q, $timeout, $rootScope, $document, LocationService) {
    return {
        require: '?ngModel',
        restrict: 'E',
        templateUrl: 'src/ionGooglePlaceTemplate.html',
        replace: true,
        scope: {
            searchQuery: '=ngModel',
            locationChanged: '&',
            // radius: '='
        },
        link: function(scope, element, attrs, ngModel) {
            var style = attrs.getplace;
            try{var index = attrs.index;}catch(err){console.log(err)}
            // if (attrs.index) {var index = attrs.index; }
            scope.dropDownActive = false;
            var service = new google.maps.places.AutocompleteService();
            var searchEventTimeout = undefined;
            var latLng = null;
            navigator.geolocation.getCurrentPosition(function(position) {
                latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            });
            var searchInputElement = angular.element(element.find('input'));
            var componentAddressForm = {
                locality: 'long_name',
                administrative_area_level_1: 'short_name',
                postal_code: 'short_name'
            };
            scope.selectLocation = function(location) {
                var data = [];
                data.index=index;
                scope.dropDownActive = false;
                scope.searchQuery = location.description;
                if (style == "true") {
                    var place_id = location.place_id;
                    LocationService.getDetails(place_id).then(function(location) {
                        if (scope.locationChanged) {
                            angular.forEach(location.address_components, function(item) {
                                var addressType = item.types[0];
                                if (componentAddressForm[addressType]) {
                                    var val = item[componentAddressForm[addressType]];
                                    data[addressType] = val;
                                }
                            })
                            scope.locationChanged()(data);
                        }
                    })
                }
            };
            // if (!scope.radius) {
            //     scope.radius = 1500000;
            // }
            scope.locations = []
            scope.$watch('searchQuery', function(query) {
                if (query) {
                    LocationService.searchAddress(query).then(function(result) {
                        scope.locations = result;
                    }, function(status) {
                        scope.locations = "There was an error :( " + status;
                    });
                };
            });
            var onClick = function(e) {
                e.preventDefault();
                e.stopPropagation();
                scope.dropDownActive = true;
                scope.$digest();
                searchInputElement[0].focus();
                setTimeout(function() {
                    searchInputElement[0].focus();
                }, 0);
            };
            var onCancel = function(e) {
                setTimeout(function() {
                    scope.dropDownActive = false;
                    scope.$digest();
                }, 200);
            };
            element.find('input').bind('click', onClick);
            element.find('input').bind('blur', onCancel);
            element.find('input').bind('touchend', onClick);
            if (attrs.placeholder) {
                element.find('input').attr('placeholder', attrs.placeholder);
            }
        }
    };
}).run(["$templateCache", function($templateCache) {
    $templateCache.put("src/ionGooglePlaceTemplate.html", template);
}]);