// helpers

function notyfication(type,timeout){
    return function(msg){
        noty({
            'text': msg,
            'layout': "bottomRight",
            'type': type,
            'timeout': timeout
        });
    };
}
var notyError = notyfication('error',2500);
var notySuccess = notyfication('success',2500);

function editor(returnpath){
    return function($scope, $http, $route, $routeParams, $window, $location) {
        $scope.member = {"id": $routeParams.id};
        $http.get("/members/api/member/"+$scope.member.id).then(function(response){
            $scope.member = response.data;
        });

        $scope.send = function() {
            $http.put("/members/api/member/"+$scope.member.id, $scope.member).then(function(data){
                notySuccess("Jäsentiedot tallennettu");
                $location.path(returnpath);
            });
        }
        $scope.cancel = function() { //user canceled. return to list
            $location.path(returnpath);
        }
    }
}
app.directive('ngConfirmClick',
[
function()
{ return {
	link: function (scope, element, attr)
	{
		var clickAction = attr.confirmedClick;
		element.bind('click',function (event)
		{
			noty({
				text: 'Oletko aivan varma? T. Lasse Lehtinen',
				layout: 'bottomRight',
				buttons: [
					{
						addClass: 'btn btn-danger', text: 'Kyllä', onClick: function($noty) {
							// this = button element
							// $noty = $noty element
							$noty.close();
							scope.$eval(clickAction)
						}
					},
					{
						addClass: 'btn btn-primary', text: 'Ei', onClick: function($noty) {
							$noty.close();
						}
					}
				]
			});
		});
	}
}}]);

// controllers

app.controller("getController", function($scope, $http, $window, $location){
	$scope.members = [];
	$scope.getFunction = function() {
		$http.get("/members/api/members").then(function(response){
			$scope.members = response.data;
			// map trues and falses to more user-friendly format
			_.each($scope.members, function(m){
				m.jas = m.jas ? "Kyllä" : "Ei";
				m.AYY = m.AYY ? "Kyllä" : "Ei";
			});
      $scope.shown_members = $scope.members;
		});
	};
	$scope.getFunction();
    $scope.updatePayment= function(id){
        $http.put("/members/api/member/"+id,{paid:moment().format("YYYY-MM-DD kk:mm:ss") }).then(function(resp){
            $scope.getFunction();
        });
    };
    $scope.loadCSV = function() {
        window.location = "/members/api/getCSV";
    };
	$scope.delete_member = function(id) {
		$http.delete("/members/api/member/" + id).then(
			function(response) {
                notySuccess("Poistaminen onnistui")
				$scope.getFunction();
			},
			function(response) {
				notyError("Epäonnistui. Yritä uudelleen.");
				$scope.getFunction();
			}
		);
	};

	$scope.datePicker = null;
	$scope.filter_by_date = function() {
		if ($scope.datePicker == null)
		{
      $scope.shown_members = $scope.members;
		}
		else
		{
      $scope.shown_members = [];
      for (var i = 0; i < $scope.members.length; i++)
      {
        if (moment($scope.members[i].paid) < $scope.datePicker)
        {
          $scope.shown_members.push($scope.members[i]);
        }
      }
		}
	};
	$scope.clear_filter = function() {
		$scope.datePicker = null;
		$scope.getFunction();
	};

	$scope.$watch('datePicker', function(newValue, oldValue) {
		$scope.filter_by_date();
	});
});

app.controller("postController", function($scope, $http, $location) {
	$scope.member = {};
	$scope.send = function() {
		$http.post("/members/api/member/", $scope.member).then(function(data){
            notySuccess("Jäsen lisätty!");
			$location.path("/list");
		});
	}
});

app.controller("applController", function($scope, $http, $route, $routeParams, $window, $location){
	$scope.applGetFunction = function() {
		$http.get("/members/api/requests").then(function(response){
			$scope.applications = response.data;
			_.each($scope.applications, function(a){
				a.member.jas = a.member.jas ? "Kyllä" : "Ei";
				a.member.AYY = a.member.AYY ? "Kyllä" : "Ei";
			});
		});
	};
	$scope.applGetFunction();
	$scope.send_appl = function(id) {
		$http.post("/members/api/request/" + id).then(
			function(response) {
			    notySuccess("Hakemus hyväksytty");
				$scope.applGetFunction();
			},
			function(response) {
                notyError("Hakemuksen hyväksyminen epäonnistui");
				$scope.applGetFunction();
			}
		);
	};
	$scope.delete_appl = function(id) {
		$http.delete("/members/api/request/" + id).then(
			function(response) {
				notySuccess("Hakemus hylätty!");
                $scope.applGetFunction();
			},
			function(response) {
				notyError("Hakemuksen hylkäys epäonnistui");
				$scope.applGetFunction();
			}
		);
	};
});

app.controller("editController",editor("/list"));
app.controller("appleditController", editor("/applications"));

app.controller("addManyController", function($scope, $http, $window) {
	$scope.memberData = '';
	$scope.sendCSV = function() {
		$http.post("/members/api/csvimport", $scope.memberData).then(
			function(response) {
				notySuccess("Lähetys onnistui");
				$window.location.reload();
			},
			function(response) {
				notyError("Lähetys epäonnistui");
			}
		);
	};
});
