require('./model');
require('./resource');
import { BaseViewModel } from '../master/baseViewModel.js';
import { DynamicTableForm, DynamicTableDataViewModel } from './model';

export function DynamicTableViewModel() {
    var self = this;
    self.showTableData = ko.observable(false);
    self.createBtn = function () {
        self.getLastPriority(function (res) {
            if (res !== null) {
                _h.kocnx()
                    .openForm(new DynamicTableForm(self, false, res));
            }
        });
    }
    self.editBtn = function () {
        self.getLastPriority(function (res) {
            if (res !== null) {
                _h.kocnx()
                    .openForm(new DynamicTableForm(self, true, res));
            }
        });
    }
    self.archiveBtn = function () {
        self.changeArchiveState(true);
    }
    self.unArchiveBtn = function () {
        self.changeArchiveState(false);
    }
    self.archivesBtn = function () {
        self.changeArchiveState(true);
    }
    self.unArchivesBtn = function () {
        self.changeArchiveState(false);
    }
    self.deleteDataBtn = function () {
        var selectedRecord = self.multiCommandExecute("selectedRowRecord");
        var confirmText = toast.createMessage("DynamicTableData", 'delrange', null, 'confirm');
        _h.confirmDeleteAlert(confirmText,
            function (res) {
                if (res) {
                    self.apiService.request({
                        name: "/api/dynamictabledata/delete",
                        data: { id: selectedRecord.id() },
                        success: function (data) {
                            toast.success("DynamicTableData", 'delrange');
                        },
                        error: function () {
                            toast.error("DynamicTableData", 'delrange');
                        }
                    });
                }
            });
    }
    self.changeArchiveState = function (action) {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            model = {
                archive: action,
                idList: idList
            };
        }
        var items = self.multiCommandExecute("selectedItems");
        self.apiService.request({
            name: "putArchiveState",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (model.idList.length > 1) {
                        if (action)
                            toast.success(self.entityName, 'custom', "Archives");
                        else
                            toast.success(self.entityName, 'custom', "UnArchives");
                    }
                    if (model.idList.length === 1) {
                        if (action)
                            toast.success(self.entityName, 'custom', "Archive");
                        else
                            toast.success(self.entityName, 'custom', "UnArchive");
                    }
                    if (action === false) {
                        self.afterCreate(data.models);
                    }
                    else {
                        if (_h.isNullOrEmpty(self.groupProperty())) {
                            for (var i = 0; i < items.length; i++) {
                                var item = items[i];
                                self.records.remove(item);
                                self.total(self.total() - model.idList.length);
                            }
                        } else {
                            for (var d = 0; d < items.length; d++) {
                                var gItem = items[d];
                                var gParent = gItem.gParent;
                                gParent.list.remove(gItem);
                            }
                        }
                    }
                }
            },
            error: function () {
                if (model.idList.length > 1) {
                    if (action)
                        toast.error(self.entityName, 'custom', "Archives");
                    else
                        toast.error(self.entityName, 'custom', "UnArchives");
                }
                if (model.idList.length === 1) {
                    if (action)
                        toast.error(self.entityName, 'custom', "Archive");
                    else
                        toast.error(self.entityName, 'custom', "UnArchive");
                }
            }
        });
    }
    self.importExcelBtn = function () {
        if (self.showTableData())
            _h.kocnx().importFileBtn(self.childModel().tableId(), self, "Excel", false);
        else
            _h.kocnx().importFileBtn(undefined, self, "Excel", true);
    }
    self.viewTableData = function (item) {
        item = item[0];
        var cols = [];
        var idObj = {
            fa: '#',
            colName: 'id',
            tablecol: false,
            visibleCol: false,
            sortDir: "None",
            alias: null,
            type: "template",
            templateName: "checkbox-table-template"
        };

        cols.push(idObj);
        if (!_h.isNullOrEmpty(item.fields()))
            for (var i = 0; i < item.fields().length; i++) {
                var field = item.fields()[i];
                var order = field.order().toString();
                var obj = {
                    fa: field.fieldName(),
                    colName: order,
                    tablecol: true,
                    visibleCol: true,
                    sortDir: "None",
                    alias: null,
                    type: "string"
                };
                if (i === 0)
                    obj.sortDir = "Ascending";

                cols.push(obj);
            }

        var model = new DynamicTableDataViewModel(cols);
        model.tableId(item.id());
        model.tableName(item.name());
        model.tableCode(item.code());
        self.childModel(model);
        self.childModel().init();
        self.showTableData(true);
    }
    self.returnBack = function () {
        self.showTableData(false);
        self.childModel(null);
    }
    self.copyBtn = function (type, parent) {
        var item = self.getSelectedRecord();
        var model = {
            id: item.id(),
            copyType: Number(type)
        };
        self.apiService.request({
            name: "postCopy",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    toast.success(self.entityName, 'custom', "Copy");
                    self.afterCreate(data.models);
                }
            },
            error: function () {
                toast.error(self.entityName, 'custom', "Copy");
            }
        });
    };
    self.connectManBtn = function () {
        _h.kocnx().openConnectMan(49, "connectManCaption");
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "DynamicTable",
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete", "putarchivestate", "postcopy"]
        },
        buttons: [
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            { name: 'connectMan', access: true, icon: 'DatabaseLink', cMenu: true },
            { name: 'archive', access: true, icon: 'Archive', cMenu: true },
            { name: 'unArchive', access: true, icon: 'UnArchive', cMenu: true },
            { name: 'archives', access: true, icon: 'Archive', cMenu: true },
            { name: 'unArchives', access: true, icon: 'UnArchive', cMenu: true },
            {
                name: 'copy', access: true, cMenu: true,
                templateName: "copydynatable-button-template",
                icon: 'Copy'
            },
            { name: 'deleteData', access: true, icon: 'ListDelete', cMenu: true },
            { name: 'up', access: true, icon: 'Up', cMenu: true },
            { name: 'down', access: true, icon: 'Down', cMenu: true },
            { name: 'importExcel', access: true, icon: 'ImportExcel', 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 }
        ],
        filters: [
            { name: 'showArchived', type: "bool", source: "null" }
        ],
        sortDirection: "Ascending",
        sortProperty: "priority",
        context: self,
        cols: dynamictableModelRes,
        extraParams: ["lastPriority"],
        saveState: true,
        getList: true,
        selectRow: true,
        contextMenu: true,
        isMultiSelectRows: true,
        searchKeyType: "enter",
        folderManagement: true,
        showDetails: {
            headerIcon: "fa fa-2x fa-columns",
            headerRes: "fieldListCaption",
            template: "fields-details-template",
            toggleParam: "fieldsShow",
            toggleFunc: "toggleFields"
        },
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        var context = _h.kocnx();
        var permitPeriodEdit = context.permitPeriodEdit();
        var data = self.multiCommandExecute("btnVisibilityData4");
        if (_h.isNullOrEmpty(data))
            return;
        var temp = data[0];
        var archiveCount = data[1];
        var unArchiveCount = data[2];
        var selectedList = data[3];
        if (selectedList === 0) {
            self.visdelete(false);
            self.visedit(false);
            self.visup(false);
            self.visdown(false);
            self.visarchive(false);
            self.visunArchive(false);
            self.visarchives(false);
            self.visunArchives(false);
            self.visdeleteData(false);
            self.visdelete(false);
            self.viscopy(false);
        }
        if (selectedList === 1) {
            self.visdelete(true);
            self.visedit(true);
            self.visup(temp.priority() > 1);
            self.visdown(self.lastPriority() !== temp.priority());
            self.visunArchive(permitPeriodEdit && unArchiveCount >= 0 && archiveCount > 0);
            self.visarchive(permitPeriodEdit && unArchiveCount >= 0 && archiveCount === 0);
            self.visarchives(false);
            self.visunArchives(false);
            self.visdeleteData(permitPeriodEdit && !context.periodItem().cl);
            self.viscopy(true);
        }
        if (selectedList > 1) {
            self.visdelete(false);
            self.visedit(false);
            self.visup(false);
            self.visdown(false);
            self.visarchive(false);
            self.visunArchive(false);
            self.visarchives(permitPeriodEdit && unArchiveCount >= 0 && archiveCount === 0);
            self.visunArchives(permitPeriodEdit && unArchiveCount >= 0 && archiveCount > 0);
            self.visdeleteData(false);
            self.viscopy(false);
        }
        self.visconnectMan(true);
        self.viscreate(true);
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
        self.visimportExcel(true);
    });
    self.toggleFields = function (item) {
        item.fieldsShow(!item.fieldsShow());
    };
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getFolderList();
    };
}