define([ 'plugins/router', 'durandal/app', 'durandal/system', 'knockout', 'services/datacontext', 'services/logger'], function (router, app, system, ko, datacontext, logger) {

    var isDeleting = ko.observable(false),
        isSaving = ko.observable(false),
        isDeleted = ko.observable(false),
        user = ko.observable(),

        editing = ko.observable(false),
        isNew = ko.observable(0),

        activate = function (id) {
            id == 0 ? user(datacontext.createUser()) : datacontext.getUserById(id, user);
        },
        cancel = function () {
            datacontext.cancelChanges();
        },
        goBack = function () {
            router.navigateBack();
        },
        hasChanges = ko.computed(function () {
            return datacontext.hasChanges();
        }),
        canSave = ko.computed(function () {
            return hasChanges() && !isSaving();
        }),
        save = function () {
            isSaving(true);
            return datacontext.saveChanges().fin(complete);
            function complete() {
                isSaving(false);
                router.navigate('#/user/' + user().id());
            }
        },
        saveClose = function () {
            save().then(success).fail(failed);

            function success() {
                router.navigate('#/users');
            }

            function failed(error) {
                var errorMsg = 'Error: ' + error.message;
                logger.logError(errorMsg, error, system.getModuleId(vm), true);
            }
        },
        deleteUser = function () {
            isDeleting(true); // prevent leaving during delete workflow
            var msg = 'Delete user "' + user().name() + '" ?';
            return app.showMessage(msg, 'Confirm Delete', ['Yes', 'No'])
                .then(confirmDelete);

            function confirmDelete(selectedOption) {
                if (selectedOption === 'Yes') {
                    // mark for deletion, then save
                    user().entityAspect.setDeleted();
                    save().then(success).fail(failed);
                } else {
                    isDeleting(false);
                }

                function success() {
                    isDeleted(true); // to navigate away now
                    isDeleting(false); // to navigate away now
                    router.navigate('#/users');
                }

                function failed(error) {
                    isDeleting(false);
                    cancel();
                    var errorMsg = 'Error: ' + error.message;
                    logger.logError(errorMsg, error, system.getModuleId(vm), true);
                }
            }
        },
        canDeactivate = function () {
            if (isDeleting()) {
                return false;
            } // Prevent leaving

            if (isDeleted()) {
                return true;
            } // Prevent leaving

//            if (hasChanges()) {
//                var name = 'Do you want to leave "' + user().name() + '" ?';
//                var msg = 'Navigate away and cancel your changes?';
//                return app.showMessage(name, msg, ['Yes', 'No'])
//                    .then(confirm);
//            }

            return true;

            function confirm(selectedOption) {
                if (selectedOption === 'Yes') {
                    cancel();
                }
                return selectedOption;
            }
        }


    var vm = {
        activate: activate,
        user: user,
        cancel: cancel,
        canSave: canSave,
        canDeactivate: canDeactivate,
        deleteUser: deleteUser,
        goBack: goBack,
        hasChanges: hasChanges,
        save: save,
        saveClose: saveClose,
        title: 'Edit a User',
        editing: editing,
        isNew: isNew,
        editToken: function(data){
            vm.editingToken(data);
        },
        addToken: function(){
            vm.editingToken({token: '', allowed: '', restricted: '', user: vm.user()});
        },
        saveToken: function(){
            if(!vm.editingToken().id)
                datacontext.createToken(vm.editingToken());
            vm.editingToken(null);
            vm.save();
        },
        cancelToken: function(){
            vm.editingToken(null);
        },
        removeToken: function(data){
            app.showMessage('Are you sure you want to delete: ' + data.token() + '?', 'Delete Confirmation', ['Yes', 'No']).then(function(dialogResult){
                if(dialogResult === "Yes"){
                    datacontext.remove(data);
                    vm.editingToken(null);
                    vm.save();
                }
            });

        },
        editingToken: ko.observable(null)
    };

    return vm;
});