'use strict';

angular
	.module('sloDialectsApp')
	.component('app', {
		templateUrl: 'components/main/main.template.html',
		controller: ['$filter', 'geojsonService', '$q', '$scope', '$rootScope', '$timeout', '$uibModal', '$http', 'leafletData', function MainController($filter, geojsonService, $q, $scope, $rootScope, $timeout, $uibModal, $http, leafletData) {

			var vm = this;
			var colorDialect = $filter('colorDialect');
			var patternDialect = $filter('patternDialect');
			var nameDialect = $filter('nameDialect');
			var nameDialectGroup = $filter('nameDialectGroup');

			var leafletMap;

			leafletData.getMap('karta').then(function(_map) {
                vm.info = "Karta slovenskih narečnih besedil se nalaga ...";
                leafletMap = _map;
			});

			vm.center = {
				lat: 46.05,
				lng: 14.53,
				zoom: 9
			};

			vm.maxBounds = {
				northEast: {
					lat: 47.2,
					lng: 17
				},
				southWest: {
					lat: 45,
					lng: 13
				}
			}

			function style(feature) {
				var id = feature.properties.id;
				var pattern = patternDialect(id);
				var fillPattern = false;
				if( pattern.type == 'stripes' ){
					fillPattern = new L.StripePattern( pattern.config )
					fillPattern.addTo(leafletMap);
				} else if( pattern.type == 'circles' ){
					var shape = new L.PatternCircle( pattern.config );
					fillPattern = new L.Pattern({width:20, height:20});
					fillPattern.addShape(shape);
					fillPattern.addTo(leafletMap);
				}

				var dashArray = 'none';
				var weight = 1;
				if(id.indexOf('podnarecje') > -1){
					dashArray = '5';
				}
				if(id.indexOf('narecna_skupina') > -1){
					weight = 3;
				}

                return {
					fillColor: colorDialect(id),
					fillPattern: fillPattern,
                    weight: weight,
                    opacity: 1,
                    color: '#000000',
                    dashArray: dashArray,
					fillOpacity: 0.8
                };
            }

			geojsonService.getAllSorted().then(function (response) {
				vm.geojson = {
					data: response.data,
					style: style,
					resetStyleOnMouseout: true,
					onEachFeature: onEachFeature,
					resetStyleOnMouseout: true
				}
			});

			$rootScope.layersArr = [];

			function onEachFeature(feature, layer) {

				$rootScope.layersArr[feature.properties.id] = layer;

				layer.on({
					mouseover: highlightFeature,
					mouseout: resetHighlight
				});
			}

			function highlightFeature(e) {
				var id = e.target.feature.properties.id;
				vm.info = id;

				if( id.indexOf('narecna_skupina') === -1){ // do not highlight dialect groups
					var layer = e.target;
					layer.setStyle({
						weight: 5,
						color: "#b23636"
					});
				}
			}

			function resetHighlight(e) {
				var layer = e.target;
				var resetWeight = 1;
				if(layer.feature.properties.id.indexOf('narecna_skupina') > -1){
					resetWeight = 3;
				}
				layer.setStyle({
					weight: resetWeight,
					color: "#000000"
				});
			}

			vm.features = [];

			vm.info = "Premaknite miško na željeno območje za prikaz imena narečja";

			getMarkers();

			function getMarkers() {
				$http.get('api/dialects').then(function (response) {
					//console.log(response.data)
					vm.markers = {};
					var i;
					for(i=0; i < response.data.length; i++){
						vm.markers[ response.data[i]['location_label'] ] = {
							lat: parseFloat(response.data[i]['location_latitude']),
							lng:  parseFloat(response.data[i]['location_longitude']),
							icon: getIconConfig( response.data[i]  ),
							title: response.data[i]['location_name']
						}
					}
				});
			}

			$scope.$on('leafletDirectiveMarker.karta.mouseover', function(event, args){
				var id = args.model.icon.dialectKey; 
				vm.info = args.model.title + " - " + nameDialect(id) + ", " + nameDialectGroup(id);
			});

			$scope.$on('leafletDirectiveMarker.karta.mouseout', function(event, args){
				resetInfoBox();
			});

			$scope.$on('leafletDirectiveMarker.karta.click', function(event, args){
				var id = args.model.icon.dialectId;
				openDialectModal(id);
			});

			$scope.$on("leafletDirectiveGeoJson.karta.mouseover", function(event, args) {
				var id = args.model.properties.id
				vm.info = id;
			});

			$scope.$on("leafletDirectiveGeoJson.karta.mouseout", function(event, args) {
				resetInfoBox();
			});
			
			function resetInfoBox(){
				vm.info = "Premaknite miško na željeno območje za prikaz imena narečja";
			}

			function getIconConfig(data){

				var label = data['location_label'];
				var dialect_key = data['dialect_key'];
				var id = data['id'];
				 
				return {
					type: 'div',
					iconAnchor: [18, 55],
					iconSize: [0, 0],
					html: '<svg x="0px" y="0px" viewBox="0 0 365 560" style="width:36px; cursor:pointer;"><g><path fill="'+colorDialect(dialect_key)+'" stroke="#000000" stroke-width="20" d="M182.9,551.7c0,0.1,0.2,0.3,0.2,0.3S358.3,283,358.3,194.6c0-130.1-88.8-186.7-175.4-186.9 C96.3,7.9,7.5,64.5,7.5,194.6c0,88.4,175.3,357.4,175.3,357.4S182.9,551.7,182.9,551.7z"/></g></svg>\
						   <div style="font-size:1.5em; color:#000000; position: absolute; top: 10px; text-align: center; width:36px;">'+label+'</div>',
					dialectKey: dialect_key,
					dialectId: id
				};
			}

			vm.openAboutModal = function () {
				var modalInstance = $uibModal.open({
					component: 'aboutComponent',
					size: 'wide'
				});
				// handle modal dismiss
				modalInstance.result.then(function () { }, function () { });
			}

			function openDialectModal (dialect_id) {
				var modalInstance = $uibModal.open({
					component: 'dialectComponent',
					size: 'wide',
					resolve: {
						// will be injected into controller
						dialectData: function () {
							return $http.get('api/dialects/' + dialect_id).then(function (response) {
								return response.data;
							}, function (err) {
								console.log('Error getting dialect', dialect_id, '-', err);
							});
						},
						analysisData: function () {
							return $http.get('api/dialects/' + dialect_id + '/analysis/').then(function (response) {
								return response.data;
							}, function (err) {
								console.log('Error getting analysis for dialect', dialect_id, '-', err);
							});
						}
					}
				});
			}

		}]
	});