require('./resource.js');
require('../../util/commonResources.js');

import { BaseViewModel } from '../master/baseViewModel.js';
import { UserContentViewModel, UserForm, UserAccessForm } from './model.js';
import { SelectItem, ResetPasswordModel } from '../master/model.js'
export function UserViewModel() {
    var self = this;
    self.getUserAccesses = function (callback) {
        var model = {
            id: self.getSelectedRecord().id()
        };
        self.apiService.request({
            name: "getAccess",
            data: model,
            success: function (data) {
                callback(data);
            },
            error: function () {
                callback(null);
            },
            messageType: 'getList',
            messageKey: "UserAccessList"
        });
    }
    self.userSelectList = ko.observableArray();
    self.getUserSelectList = function () {
        self.apiService.request({
            name: "/api/common/getuserslist",
            data: {
                controllerName: self.controllerName
            },
            success: function (data) {
                self.userSelectList.removeAll();
                if (_h.any(data)) {
                    for (var j = 0; j < data.length; j++) {
                        var target = new SelectItem(data[j]);
                        self.userSelectList.push(target);
                    }
                }
            },
            messageType: 'getSelectList',
            messageKey: "User"
        });
    }
    self.createBtn = function () {
        _h.kocnx()
            .openForm(new UserForm(self));
    }
    self.editBtn = function () {
        _h.kocnx()
            .openForm(new UserForm(self, true));
    }
    self.accessManagerBtn = function () {
        self.getUserAccesses(function (data) {
            _h.kocnx()
                .openForm(new UserAccessForm(self, data));
        });
    }
    self.editUserAccess = function (parents, btnModel, e) {
        var item = parents[1];
        var model = item.toServer();
        self.apiService.request({
            splashId: e,
            name: "postAccess",
            data: model,
            success: function (data) {
                _h.kocnx().closeForm();
                toast.success(self.entityName, 'put', 'UserAccess');
            },
            messageType: 'put',
            messageKey: "UserAccess"
        });
    }
    self.adminResetPasswordBtn = function () {
        var selectedRecord = self.getSelectedRecord();
        _h.kocnx()
            .openForm(new ResetPasswordModel(self, { "userId": selectedRecord.id() }));
    }
    self.adminResetPassword = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var model = item.toServer();
        self.apiService.request({
            splashId: e,
            name: "postAdminResetPassword",
            data: model,
            success: function (data) {
                _h.kocnx().closeForm();
                toast.success(self.entityName, 'put', 'ResetPassword');
            },
            messageType: 'put',
            messageKey: "ResetPassword"
        });
    }
    self.unlockUserBtn = function () {
        var selectedRecord = self.getSelectedRecord();
        self.apiService.request({
            name: "putUnlock",
            data: { id: selectedRecord.id() },
            success: function (data) {
                self.multiCommandExecute("changesUnlockUser",
                    !selectedRecord.locked(),
                    [selectedRecord.id()]);
                self.selectedRecord(null);
                self.selectedRowRecord(null);
                toast.success(self.entityName, 'custom', 'UnlockUser');
            },
            messageType: 'custom',
            messageKey: "UnlockUser"
        });
    }
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getUserSelectList();
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "User",
        apiService: {
            actionList: ["filterby",
                "post", "put", "postadminresetpassword",
                "isusernameunique", "postaccess", "getaccessselectlist",
                "getaccess", "putunlock"]
        },
        filters: [
            { name: 'stateType', type: "select", source: stateTypes }
        ],
        sortDirection: "Ascending",
        buttons: [
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'adminResetPassword', access: true, icon: 'ChangePassword', cMenu: true },
            { name: 'accessManager', access: true, icon: 'RoleUser', cMenu: true },
            { name: 'disable', access: true, icon: 'DocDisable', cMenu: true },
            { name: 'enable', access: true, icon: 'DocEnable', cMenu: true },
            { name: 'unlockUser', access: true, icon: 'UnlockUser', cMenu: true },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false },
            { name: 'create', access: true, cMenu: false }
        ],
        sortProperty: "id",
        context: self,
        cols: userModelRes,
        getList: true,
        saveState: true,
        selectRow: true,
        searchKeyType: "enter",
        contextMenu: true,
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        var selectedRecord = self.selectedRowRecord();
        var inListView = self.showType() === "List";
        if (!_h.isNullOrEmpty(selectedRecord)) {
            self.visedit(!inListView);
            self.visadminResetPassword(!inListView);
            self.visaccessManager(!inListView);
            self.visdisable(selectedRecord.stateType() === 1 && !inListView);
            self.visenable(selectedRecord.stateType() === 0 && !inListView);
            self.visunlockUser(selectedRecord.locked() && !inListView);
        } else {
            self.visedit(false);
            self.visadminResetPassword(false);
            self.visaccessManager(false);
            self.visdisable(false);
            self.visenable(false);
        }
        self.vishelp(!inListView);
        self.visrefresh(!inListView);
        self.vistools(true);
        self.viscreate(!inListView);
    });
    self.changeChildModel = function (target) {
        var model = new UserContentViewModel(self);
        self.childModel(model);
        self.childModel().userId(target.id());
        self.childModel().init();
    }
}