'use strict';

app.directive('timeSettings', function() {
	return {
		restrict: 'EA',
		replace:true,
		scope: {
			system: '=',
			timeZones: '='
		},
		template: '<a ng-click="showTimeSettingsModal()">Change the time settings for this system </a>',
		//<small>{{system.timezone.data.name}}</small>
		controller: function($scope, $modal, toastr, Systems) {
			var timeSettingsModal = $modal({
				scope: $scope,
				template: 'views/modal-tpls/change-tz.html',
				show: false
			});


			$scope.setTimeZone = function() {
				console.log($scope.time.format);
				var data = JSON.stringify({ id: $scope.time.zone.data.id , dst: $scope.time.zone.dst ? 1:0, time_type: $scope.time.format === 'hh:mm:ss a' ? 0:1 });
				Systems.setTimeZone(data).then(function(data) {
					console.log(data);
					$scope.system.timezone.data = angular.copy($scope.time.zone.data);
					$scope.system.timezone.dst = $scope.time.zone.dst ? 1:0;
					$scope.system.time_type = $scope.time.format === 'hh:mm:ss a' ? 0:1;
					Systems.loadSystem($scope.system);
				}).catch(function(error) {
					toastr.error(error, 'Error');
				});
			};

			$scope.checkDST = function() {
				if ($scope.time.zone.data.s_time === '0.0.0 00:00:00' || !$scope.time.zone.data.d_bias) {
					$scope.time.zone.dst = false;
				} else {
					$scope.time.zone.dst = true;
				}
			};

			$scope.showTimeSettingsModal = function () {
				$scope.time = {};
				$scope.time.zone = { data: angular.copy($scope.system.timezone.data), dst: $scope.system.timezone.dst ? true:false };
				$scope.time.format = $scope.system.time_type === 0 ? 'hh:mm:ss a': 'HH:mm:ss';
				timeSettingsModal.$promise.then(timeSettingsModal.show);       
			};
		}
	};
});