app.controller('userCtrl', ['$scope', '$location', function($scope, $location) {
		$scope.currentUrl = $location.$$path;
	}]);

app.controller('userRestaurantCtrl', ['$scope', '$rootScope', '$localStorage', '$location', 'configServ', 'requestServ',
	function($scope, $rootScope, $localStorage, $location, configServ, requestServ) {

		$scope.restaurantArray = [];
		$scope.loadRestaurant = true;
		$scope.formValidAddress = false;

		$scope.getRestaurants = function() {
			var optionsMenu = {
				param: {
					'corpid': configServ.corpId,
					'lang': $rootScope.currentLocal
				}
			};

			// получаем дерево категорий
			requestServ.serverCall("/api/v2/rests", optionsMenu, function(response) {
				if(response.error) {
					var options = {
						message: $rootScope.getLocale('Startup error restaurants list'),
						fullMessage: response.value,
						type: 'warning',
						callbackOk: function() {
							$scope.getRestaurants();
							$rootScope.CloseError();
						},
						callbackCancel: function() {
							$rootScope.CloseError();
							window.location.href = '#';
							console.log('cancel');
						}
					};
					$rootScope.ShowErrorMessage(options);

				} else {
					$scope.restaurantArray = response.value.data.rests;
					$scope.loadRestaurant = false;

					if($scope.restaurantArray.length == 1) {
						$scope.restaurantUser = $scope.restaurantArray[0].id.toString();
					}
				}
			});
		};

		$scope.getRestaurants();

		$scope.toSaveInfoUser = function(link, event) {
			event.preventDefault();

			if(!$scope.userRestaurantForm.$valid) {
				$scope.formValidAddress = true;
				return false;
			}
			$scope.formValidAddress = false;


			if(!$rootScope.CartInfo.cartList.length) {
				window.location.href = link;
				$scope.saveInfoUser();
			} else {
				$scope.callbackFunctionEnd = function() {
					window.location.href = link;
					$scope.saveInfoUser();
					$rootScope.CloseError();
				};

				if($rootScope.UserInfo.length != 0) {
					var options = {
						message: $rootScope.getLocale('Cart will be cleared. Continue'),
						type: 'warning',
						callbackOk: function() {
							$scope.callbackFunctionEnd();
						},
						callbackCancel: function() {
							$rootScope.CloseError();
						}
					};
					$rootScope.ShowErrorMessage(options);
				} else {
					$scope.callbackFunctionEnd();
				}
			}
		};

		$scope.saveInfoUser = function() {
			if(!$scope.userRestaurantForm.$valid) {
				return false;
			}

			$rootScope.UserInfo.typeDelivery = 'restaurant';

			$scope.deleteLocalProducts();

			angular.forEach($scope.restaurantArray, function(item, key) {
				if($scope.restaurantUser == item.id) {
					$rootScope.UserInfo.restaurantInfo = item;
				}
			});

			//currencies

			$scope.saveUser();
			$scope.clearCart();
		};
}]);

app.controller('userAddressCtrl', ['$scope', '$rootScope', '$localStorage', '$http', 'configServ',
	function($scope, $rootScope, $localStorage, $http, config) {

		$scope.toMap = false;
		$scope.loadMap = false;
		if($localStorage.UserInfo) {
			$scope.addressDelivery = $localStorage.UserInfo.addressDelivery || {};
		} else {
			$scope.addressDelivery = {};
		}
		$scope.resultPoints = [];
		$scope.formValidAddress = false;

		$scope.getCoordinateRest = function(address) {
			$http({method: "get", url: "https://geocode-maps.yandex.ru/1.x/?geocode=" + address + "&format=json" }).
				then(function(response) {
					if(response.data.response.GeoObjectCollection == undefined || response.data.response.GeoObjectCollection.featureMember[0] == undefined) {
						$scope.loadMap = false;
						$rootScope.ShowErrorMessage({
							message: $rootScope.getLocale('Error adding map'),
							type: 'error'
						});
						return false;
					}
					var GeoObject = response.data.response.GeoObjectCollection.featureMember[0].GeoObject;

					var Country = GeoObject.metaDataProperty.GeocoderMetaData.AddressDetails.Country;
					var points = GeoObject.Point.pos;

					$scope.resultPoints = points.split(' ');
					$scope.addressDelivery.fullAddress = generateFullAddress();
					$scope.addressDelivery.country = Country.CountryName;
					$scope.addressDelivery.lat = $scope.resultPoints[1];
					$scope.addressDelivery.lon = $scope.resultPoints[0];

					//$scope.addressDelivery.housing = '';

					$scope.loadMap = false;
					$scope.toMap = true;

					generateMap($scope.resultPoints[1], $scope.resultPoints[0]);

				}, function(response) {
					$rootScope.ShowErrorMessage({
						message: $rootScope.getLocale('Error creating map'),
						type: 'error'
					});
					//console.log('error');
				});
		};

		$scope.getToMap = function() {
			if(!$scope.userAddress.$valid) {
				$scope.formValidAddress = true;
				return false;
			}

			$scope.formValidAddress = false;
			$scope.loadMap = true;
			var housing = $scope.addressDelivery.housing || '';
			var stringAddress = $rootScope.getLocale('City') + ' ' + $scope.addressDelivery.city + ', ' +
								$rootScope.getLocale('Street') + ' ' + $scope.addressDelivery.street + ', ' +
								$rootScope.getLocale('House') + ' ' + $scope.addressDelivery.house + housing;

			$scope.getCoordinateRest(stringAddress);
		};

		$scope.backToForm = function() {
			$scope.toMap = false;
		};

		/**
		 * Генерим полный адресс на основе $scope.addressDelivery
		 * @returns {string}
		 */
		function generateFullAddress() {
		    var fullAddress = '';

            fullAddress += $scope.addressDelivery.city ? $rootScope.getLocale('City') + ' ' + $scope.addressDelivery.city : '';
            fullAddress += $scope.addressDelivery.street ? ', ' + $rootScope.getLocale('Street') + ' ' + $scope.addressDelivery.street.replace('ул. ', '') : '';
            fullAddress += $scope.addressDelivery.house ? ', ' + $rootScope.getLocale('House') + ' ' + $scope.addressDelivery.house : '';
            fullAddress += $scope.addressDelivery.housing ? ', ' + $rootScope.getLocale('Housing-building') + ' ' + $scope.addressDelivery.housing : '';
            fullAddress += $scope.addressDelivery.porch ? ', ' + $rootScope.getLocale('Access') + ' ' + $scope.addressDelivery.porch : '';
            fullAddress += $scope.addressDelivery.intercom ? ', ' + $rootScope.getLocale('Intercom') + ' ' + $scope.addressDelivery.intercom : '';
            fullAddress += $scope.addressDelivery.level ? ', ' + $rootScope.getLocale('Level') + ' ' + $scope.addressDelivery.level : '';
            fullAddress += $scope.addressDelivery.room ? ', ' + $rootScope.getLocale('Room') + ' ' + $scope.addressDelivery.room : '';

            return fullAddress;
        }

		function generateMap(lat, lng) {
			var latlng = new google.maps.LatLng(lat,lng);
			var options = {
				zoom: 15,
				center: latlng
			};


			if($scope.map == undefined) {
				//console.log('generate map');
				$scope.map = new google.maps.Map(document.getElementById("map"), options);
				$scope.geocoder = new google.maps.Geocoder();
				$scope.marker = new google.maps.Marker({
					map: $scope.map,
					draggable: true
				});
			}

			$scope.map.setCenter(latlng);
			$scope.marker.setPosition(latlng);

			google.maps.event.addListener($scope.marker, 'dragend', function() {
				$scope.geocoder.geocode({'latLng': $scope.marker.getPosition()}, function(results, status) {
					if (status != google.maps.GeocoderStatus.OK || !results[0]) {
                        return;
                    }

                    $scope.$apply(function () {
                        if(results[0].address_components) {
                            var lengthArr = results[0].address_components.length;

                            for(var i = 0; i < lengthArr; i++) {
                                var resultsArr = results[0].address_components[i];

                                switch (resultsArr.types[0]) {
                                    case 'country':
                                        $scope.addressDelivery.country = resultsArr.long_name;
                                        break;
                                    case 'locality':
                                        $scope.addressDelivery.city = resultsArr.long_name;
                                        break;
                                    case 'route':
                                        $scope.addressDelivery.street = resultsArr.short_name;
                                        break;
                                    case 'street_number':
                                        $scope.addressDelivery.house = resultsArr.short_name;
                                        break;
                                }
                            }
                        }

                        $scope.addressDelivery.housing = '';
                        $scope.addressDelivery.lat = $scope.marker.getPosition().lat();
                        $scope.addressDelivery.lon = $scope.marker.getPosition().lng();

						$scope.addressDelivery.fullAddress = generateFullAddress();
                    });
				});
			});
		}

		$scope.toSaveInfoDelivery = function(link, event) {
			event.preventDefault();

			if(!$rootScope.CartInfo.cartList.length) {
				window.location.href = link;
				$scope.saveInfoUserDelivery();
			} else {
				$scope.callbackFunctionEnd = function() {
					window.location.href = link;
					$scope.saveInfoUserDelivery();
					$scope.clearCart();
					$rootScope.CloseError();
				};

				if($rootScope.UserInfo.length != 0) {
					var options = {
						message: $rootScope.getLocale('Cart will be cleared. Continue'),
						type: 'warning',
						callbackOk: function() {
							$scope.callbackFunctionEnd();
						},
						callbackCancel: function() {
							$rootScope.CloseError();
						}
					};
					$rootScope.ShowErrorMessage(options);
				} else {
					$scope.callbackFunctionEnd();
				}
			}
		};

		$scope.saveInfoUserDelivery = function() {
			if(!$scope.userAddress.$valid) {
				return false;
			}

			$rootScope.UserInfo.addressDelivery = $scope.addressDelivery;
			$rootScope.UserInfo.typeDelivery = 'delivery';
			$scope.deleteLocalProducts();
			$scope.saveUser();
		};

		$scope.initMap = function() {
			var addMapScript = document.createElement('script');
			addMapScript.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&key=' + config.keyMapApiGoogle;
			document.body.appendChild(addMapScript);
		};

		$scope.initMap();
	}]);

