var { BaseModel, BaseFormModel, BaseSecondaryForm } = require('../master/baseModels.js');
require('knockout.validation');
import { BaseViewModel } from '../master/baseViewModel.js';

export class User extends BaseModel {
    constructor(model) {
        super(model);
    }
}
export class UserForm extends BaseFormModel {
    constructor(model, editMode) {
        super(model, editMode);
        this.password = ko.observable();
        this.passwordConfirm = ko.observable();
        this.setValidationObject(editMode);
        this.createForm(editMode);
    }

    setValidationObject(editMode) {
        var obj = {};
        obj.firstName = this.firstName.extend({
            required: true,
            minLength: 3,
            maxLength: 32,
            persianOnly: null
        });
        obj.lastName = this.lastName.extend({
            required: true,
            minLength: 3,
            maxLength: 32,
            persianOnly: null
        });
        obj.description = this.description.extend({ maxLength: 1024 });
        obj.userName = this.userName.extend({
            required: true,
            minLength: 4,
            remoteIsUniqueRule: { params: [this.id, "User", "userName"] },
            userNameValidation: null,
            maxLength: 20
        });
        obj.mobile = this.mobile.extend({
            persianMobile: null,
            numberOnly: null,
            minLength: {
                params: 11,
                message: "شماره تلفن همراه باید 11 کاراکتر عددی باشد"
            },
            maxLength: {
                params: 11,
                message: "شماره تلفن همراه باید 11 کاراکتر عددی باشد"
            }
        });
        obj.phoneNumber = this.phoneNumber.extend({ phoneNumberCheck: null });
        obj.email = this.email.extend({
            englishOnly: null,
            email: true
        });
        obj.fax = this.fax.extend({ phoneNumberCheck: null });
        obj.location = this.location.extend({
            maxLength: 32,
            persianOnly: null
        });

        if (!editMode) {
            var min = _h.getSd().pmc;
            obj.password = this.password.extend({
                required: {
                    onlyIf: function () {
                        return !this.editMode();
                    }.bind(this)
                },
                englishOnly: true,
                passwordComplexity: [min]
            });

            obj.passwordConfirm = this.passwordConfirm.extend({
                required: {
                    onlyIf: function () {
                        return !this.editMode();
                    }.bind(this)
                },
                confirmPassword: { params: this.password }
            });
        }
        this.validationObject = ko.validatedObservable(obj);
    }

    createForm(editMode) {
        const controls = [
            this.createLine({ t: 'txb', val: this.firstName },
                { t: 'txb', val: this.lastName }),
            this.createLine({ t: 'txb', val: this.phoneNumber },
                { t: 'txb', val: this.mobile }, true, 30),
            this.createLine({ t: 'txb', val: this.userName, dis: this.editMode }, null, true, 30),
            this.createLine({ t: 'txb', val: this.email }, null, true, 30)
        ];

        if (!editMode) {
            controls.push(this.createLine({ t: 'tm', templateName: 'passwordfield-form-t' }, undefined, true, 30, 0));
        }
        controls.push(this.createLine({ t: 'txb', val: this.location },
            { t: 'txb', val: this.fax }, true, 30));

        controls.push(this.createLine({ t: 'txa', val: this.description }, undefined, true, 30));

        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'create', vis: !this.editMode(), click: this.parentVM.create },
                    { name: 'edit', vis: this.editMode, click: this.parentVM.edit },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export class UserAccessForm extends BaseSecondaryForm {
    constructor(viewModel, model) {
        super(viewModel, [
            { name: "userId", type: "ob", val: model.userId },
            { name: "accessList", type: "obar", val: model.accessList },
            { name: "selector", type: "", val: "#tree_view_au" }

        ], "userRolesManagement");
        this.width = "50%";
        this.createForm();
        this.configTools();
    }
    configTools() {
        setTimeout(function () {
            $(this.selector).treeView({
                tType: "CompanyAccessUser",
                location: "CompanyAccessUser",
                nodes: this.accessList,
                rootId: "1",
                showAccessList: this.showAccessList,
                selfParent: this
            });
        }.bind(this), 400);
    }
    toServer() {
        let model = {
            userId: this.userId(),
            accessList: []
        };
        model.accessList = $(this.selector).treeView("getCompanyAccess");
        return model;
    }
    expandAll() {
        $(this.selector).treeView("expandAll");
    }
    collapseAll() {
        $(this.selector).treeView("collapseAll");
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'useraccess-form-t' }, undefined, true, 0, 0),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: "custom", resText: 'userAccessEditBtn', vis: true, click: this.parentVM.editUserAccess },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export class UserContent extends BaseModel {
    constructor(model) {
        super(model);
    }
}
export function UserContentViewModel(parent) {
    var self = this;
    self.parentModel = parent;
    ko.utils.extend(self, new BaseViewModel({
        entityName: "UserContent",
        apiService: {
            actionList: ["filterby"]
        },
        filters: [
            { name: 'userId', type: "select", source: self.parentModel.userSelectList },
            { name: 'startDate', type: "datepiker" },
            { name: 'endDate', type: "datepiker" },
            { name: 'actionNames', type: "multiselect", source: actionNames.filter(a => a.accountFilter), groupBy: "group" },
            { name: 'resultState', type: "select", source: resultStates },
            { name: 'unknownUser', type: "bool" },
        ],
        buttons: [
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false },
        ],
        sortDirection: "Ascending",
        sortProperty: "id",
        context: self,
        saveState: true,
        cols: usercontentModelRes,
        isMultiSelectRows: false,
        selectRow: true,
        contextMenu: false,
        getList: true,
        searchKeyType: "enter",
        tableClass: "table ko-tbl ko-tbl-child",
        tableStyle: "table-layout: fixed;margin-top:10px;font-size:11px;",
        resizable: true
    }));
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.userId.subscribe(function (newValue) {
            self.parentModel.changeShowBlock('fullDetails');
        });
    }
    self.btnVisibility = ko.computed(function () {
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
    });
    self.clearSearchBoxes = function () {
        for (var p in self.filters) {
            if (self.filters.hasOwnProperty(p)) {
                var target = self.filters[p];
                switch (target.type) {
                    case "multiselect":
                        self[target.name].removeAll();
                        break;
                    default:
                        self[target.name](target.def);
                        break;
                }
            }
        }
        self.searchKey("");
        self.pageNumber(1);
        self.getRecords();
    }
}