/* Controllers for member register views */

/* Generator function to create a "noty" notification function */
function notyfication(type, timeout) {
    return function(msg) {
        noty({
            'text': msg,
            'layout': "bottomRight",
            'type': type,
            'timeout': timeout
        });
    };
}

/* Create functions to show error and success notifications in the bottom
 * right corner of the viewport
 *
 * These functions take a single message string as a parameter */
var notyError = notyfication('error', 2500);
var notySuccess = notyfication('success', 2500);

function memberDataEditor(returnPath) {
    return function($scope, $http, $window, $location) {
        var id = memberId;
        console.log("id: " + id);
        $http.get("/members/api/member/" + id).then(function(response) {
            $scope.member = response.data;
        });

        $scope.send = function() {
            $http.put("/members/api/member/" + id, $scope.member).then(function(response){
                notySuccess("Jäsentiedot tallennettu");
                $window.location = returnPath;
            });
        }
        $scope.cancel = function() { //user canceled. return to list
            $window.location = 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) {
                        $noty.close();
                        scope.$eval(clickAction);
                    }
                },
                {
                    addClass: 'btn btn-primary', text: 'Ei', onClick: function($noty) {
                        $noty.close();
                    }
                } ]
			} );
		});
	}
}}]);

// controllers

app.controller("getController", function($scope, $document, $http){
    /* List of all members that are fetched from the database */
	$scope.members = [];

    /* Fetch all members from the database and show all members in the table */
    $scope.updateMembers = 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;
        });
    };

    /* Fetch a single member from the database by id and update its row */
    $scope.updateMember = function(id) {
        $http.get("/members/api/member/" + id).then(function(response) {
            for (var i = 0; i < $scope.shown_members.length; i++) {
                var member = $scope.shown_members[i];
                if (String(member.id) == String(id)) {
                    member = response.data;
                    member.jas = member.jas ? "Kyllä" : "Ei";
                    member.AYY = member.AYY ? "Kyllä" : "Ei";

                    $scope.shown_members[i] = member;
                }
            }
        });
    };

    /* Update the payment date of a single member to the current time and send
     * the member to the database */
    $scope.updatePayment= function(id){
        $http.put("/members/api/member/"+id, { paid: moment().format("YYYY-MM-DD kk:mm:ss") }).then(function(response) {
            $scope.updateMember(id);
            notySuccess("Maksupäivämäärä päivitetty.");
        });
    };
    
    /* Redirect the browser to the CSV dump download endpoint */
    $scope.loadCSV = function() {
        window.location = "/members/api/getCSV";
    };

    /* Delete a single member by id */
	$scope.deleteMember = function(id) {
		$http.delete("/members/api/member/" + id).then(
			function(response) {
                notySuccess("Poistaminen onnistui")
				$scope.updateMembers();
			},
			function(response) {
				notyError("Epäonnistui. Yritä uudelleen.");
				$scope.updateMembers();
			}
		);
	};

    $scope.filterByDateComparison = function(members, datePicker, comparison) {
        if (datePicker == null) {
            return members;
        }

        var result = [];
        for (var i = 0; i < members.length; i++) {
            if (comparison(members[i], datePicker)) {
                result.push(members[i]);
            }
        }
        return result;
    };

    /* Do a lazy search on the first name, last name and email fields
     * If at least one of the aforementioned fields contains any of the search terms
     * the search will be positive */
    $scope.filterBySearch = function(members) {
        if ($scope.searchFilter == null) {
            return members;
        }

        var filterSearch = $scope.searchFilter.trim();
        if (filterSearch.length == 0) {
            return members;
        }

        var names = filterSearch.split(" ");
        var result = [];
        for (var i = 0; i < members.length; i++) {
            var member = members[i];
            for (var j = 0; j < names.length; j++) {
                var name = names[j].trim().toLowerCase();
                if (name.length == 0) continue;

                if (member.first_name.toLowerCase().includes(name)
                        || member.last_name.toLowerCase().includes(name) 
                        || member.email.toLowerCase().includes(name)) {

                    result.push(member);
                    break;
                }
            }
        }
        return result;
    }

    /* Run all filters on the members list */
    $scope.doFilter = function() {
        var result = $scope.members;
        result = $scope.filterByDateComparison(result, $scope.addedBeforeDatePicker, function(member, date) {
            return moment(member.created) < date });
        result = $scope.filterByDateComparison(result, $scope.addedAfterDatePicker, function(member, date) {
            return moment(member.created) >= date });
        result = $scope.filterByDateComparison(result, $scope.paidBeforeDatePicker, function(member, date) {
            return moment(member.paid) < date });
        result = $scope.filterByDateComparison(result, $scope.paidAfterDatePicker, function(member, date) {
            return moment(member.paid) >= date });
        result = $scope.filterBySearch(result);

        $scope.shown_members = result;
    }

    /* Clear all filter fields and reset the table view */
	$scope.clearFilter = function() {
        $scope.paidBeforeDatePicker = null;
        $scope.paidAfterDatePicker = null;
		$scope.addedBeforeDatePicker = null;
        $scope.addedAfterDatePicker = null;
        $scope.searchFilter = null;
		$scope.updateMembers();
	};

    /* Run filters on enter keypress in search bar */
    $scope.pressKeyOnSearch = function(keyEvent) {
        /* 13 is the id of the enter key */
        if (keyEvent.which === 13) {
            $scope.doFilter();
        }
    };

    /* Start by resetting the whole thing */
    $scope.clearFilter();
});

/* Controller for adding a member */
app.controller("postController", function($scope, $http, $location) {
	$scope.member = {};
	$scope.send = function() {
		$http.post("/members/api/member/", $scope.member).then(function(response){
            notySuccess("Jäsen lisätty!");
		});
	}
});

/* Controller for application page */
app.controller("applController", function($scope, $http){
	$scope.applUpdateAll = 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.applUpdateAll();
	$scope.sendAppl = function(id) {
		$http.post("/members/api/request/" + id).then(
			function(response) {
                notySuccess("Hakemus hyväksytty");
				$scope.applUpdateAll();
			},
			function(response) {
                notyError("Hakemuksen hyväksyminen epäonnistui");
				$scope.applUpdateAll();
			}
		);
	};
	$scope.deleteAppl = function(id) {
		$http.delete("/members/api/request/" + id).then(
			function(response) {
				notySuccess("Hakemus hylätty!");
                $scope.applUpdateAll();
			},
			function(response) {
				notyError("Hakemuksen hylkäys epäonnistui");
				$scope.applUpdateAll();
			}
		);
	};
});

app.controller("editController", memberDataEditor("/members/list"));
app.controller("applEditController", memberDataEditor("/members/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");
			}
		);
	};
});
