import { ApiService } from "../util/apiService.js";

ko.components.register('ko-select', {
    viewModel: function (params) {
        var self = this;
        self.randomId = _h.createRandomNumber();
        self.id = "select-ul" + self.randomId;
        self.type = params.type;
        self.tagManager = params.tagManager || false;
        self.refreshFunc = params.refreshFunc;
        self.groupBy = params.groupBy;
        self.controlName = ko.observable(params.name);
        self.parentForm = params.parent;
        self.itemType = params.itemType;
        self.apiAddress = params.apiAddress;
        if (params.disable === true || params.disable === false) {
            self.disable = ko.observable(params.disable);
        }
        else if (!_h.isNullOrEmpty(params.disable)) {
            self.disable = params.disable;
        }
        else {
            self.disable = ko.observable(false);
        }
        if (params.bindTo) {
            params.bindTo.subscribe(function (newValue) {
                switch (self.type) {
                    case "multi":
                        self.values.removeAll();
                        break;
                    default:
                        self.value(undefined);
                        break;
                }
                if (self.parentForm["onSelect"])
                    self.parentForm.onSelect(self.controlName());
                self.buildList();
            });
        }
        self.params = params;
        self.filter = params.filter;
        self.value = params.value;
        self.values = params.values;
        self.input = ko.observable();
        self.list = params.options;
        if (params.optionsListVar)
            self.list = self.parentForm[params.optionsListVar];
        self.renderFunc = params.renderFunc;
        self.isComparativePeriodSelect = false;
        self.fillComparativePeriodSelect = function () {
            var name = ko.isObservable(params.name) ? params.name() : params.name;
            name = name + "";
            self.isComparativePeriodSelect = periodCustomItem.indexOf(name) !== -1
                || name.indexOf("ComparativePeriod") !== -1;
        }
        self.fillComparativePeriodSelect();
        self.customShowSelect = ko.observable(self.isComparativePeriodSelect);
        if (ko.isObservable(self.list)) {
            self.list.subscribe(function (newValue, oldValue) {
                self.buildList();
            });
        }
        self.showMenu = ko.observable(false);
        if (ko.isObservable(params.placeholder)) {
            self.placeHolder = params.placeholder();
        }
        else {
            self.placeHolder = _h.getLocalizedText(params.placeholder !== undefined ? params.placeholder : "selectPlaceholder");
        }
        self.removeSelectedItem = function (item) {
            if (self.disable()) {
                self.showMenu(false);
                return;
            }
            if (self.itemType) {
                var list = ko.isObservable(self.list) ? self.list() : self.list;
                item = list[item];
            }
            item = ko.toJS(item);
            switch (self.type) {
                case "multi":
                    if (_h.any(self.values()) && self.values().indexOf(item.value) !== -1)
                        self.values.remove(item.value);
                    break;
                default:
                    self.value(undefined);
                    break;
            }
            if (self.parentForm["onSelect"])
                self.parentForm.onSelect(self.controlName());
            self.buildList();
        };
        self.onSelectedItem = function (item) {
            if (self.disable()) {
                self.showMenu(false);
                return;
            }
            if (self.itemType) {
                var list = ko.isObservable(self.list) ? self.list() : self.list;
                item = list[item];
            }

            item = ko.toJS(item);
            switch (self.type) {
                case "multi":
                    if (_h.any(self.values()) && self.values().indexOf(item.value) !== -1)
                        self.values.remove(item.value);
                    break;
                default:
                    self.value(undefined);
                    break;
            }

            self.showMenu(true);
            if (self.parentForm["onSelect"])
                self.parentForm.onSelect(self.controlName());
            self.buildList();

        };
        if (!self.tagManager)
            self.input.subscribe(function (newValue) {
                self.buildList();
            });
        self.onKeypress = function (model, evt) {
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode === 13) {
                if (self.type === "multi" && self.tagManager) {
                    var val = $(evt.target).val();
                    if (val) {
                        if (_h.isEmpty(self.values()) || self.values().indexOf(val) === -1) {
                            self.values.push(val);
                            self.addTagToList(val);
                        }
                    }
                    self.adjustInputSize();
                    self.input('');
                }
                if (self.type === "multi" && !self.tagManager) {
                    self.adjustInputSize();
                }


            } else {
                self.buildList();
            }
        };
        self.onFocusOut = function (evt) {
            $(evt.target).css("display", "none");
        }
        self.onFocusIn = function (evt) {
            $(evt.target).css("display", "inline-block");
        }
        self.removeTag = function (item) {
            ApiService.request(
                {
                    url: "/api/common/deletetags",
                    data: {
                        id: item.value,
                        controllerName: self.params.controllerName
                    },
                    success: function (data) {
                        self.removeTagFromList(item);
                    },
                    error: function (data) {

                    }
                });
        }
        self.removeTagFromList = function (item) {
            var isExist;
            for (let i = 0; i < self.list().length; i++) {
                if (self.list()[i].value === item.value)
                    isExist = self.list()[i];
            }
            if (isExist)
                self.list.remove(isExist);
        }
        self.addTagToList = function (val) {
            var isExist = false;
            for (let i = 0; i < self.list().length; i++) {
                if (self.list()[i].value === val)
                    isExist = true;
            }
            if (!isExist)
                self.list.push({ text: val, value: val });
        }
        self.adjustInputSize = function () {
            var inputTag = $("input[dataid='" + self.id + "']");
            var val = $(inputTag).val();
            if (self.type === "multi") {
                if (self.values().length > 0) {
                    inputTag.css("margin-right", "5px");
                    inputTag.css("width", "50px");
                } else {
                    inputTag.css("margin-right", "");
                    $(inputTag).css("width", "");
                }
            }
        }
        self.onSelectItem = function (item) {
            switch (self.type) {
                case "multi":
                    if (!_h.any(self.values()) ||
                        (_h.any(self.values()) && self.values().indexOf(item.value) === -1))
                        self.values.push(item.value);
                    self.input(undefined);
                    self.buildList();
                    self.adjustInputSize();
                    break;
                default:
                    self.value(item.value);
                    self.input(undefined);
                    self.showMenu(false);
                    break;
            }
            if (self.parentForm["onSelect"])
                self.parentForm.onSelect(self.controlName(), item);

        };
        self.onInputFocus = function (x, e) {
            if (self.disable()) {
                self.showMenu(false);
                return;
            }
            switch (self.type) {
                case "multi":
                    var input = $(e.target).find(".autocomplate-input");
                    if (input) {
                        $(input).focus();
                    }
                    break;
            }
            var visList = $(".drp-menu:visible");
            if (visList && visList.length > 0) {
                for (var i = 0; i < visList.length; i++) {
                    if ($(visList[i]).attr("id") !== self.id) {
                        var target = ko.contextFor(visList[i]);
                        if (target && target.$data && target.$data["showMenu"])
                            target.$data.showMenu(false);
                    }
                }
            }
            self.showMenu(true);
            self.buildList();
        };
        self.isShowItem = function (item) {
            if (self["filter"] && !self.filter(item))
                return false;
            switch (self.type) {
                case "multi":
                    if (!_h.any(self.values()) && _h.isEmpty(self.input()))
                        return true;
                    if (_h.any(self.values()) && self.values().indexOf(item.value) !== -1)
                        return false;
                    break;
                default:
                    if (_h.isEmpty(self.value()) && _h.isEmpty(self.input()))
                        return true;
                    if (!_h.isEmpty(self.value()) && self.value() == item.value)
                        return false;
                    break;
            }
            if (_h.isEmpty(self.input()) ||
                (!_h.isEmpty(self.input()) && item.text && item.text.indexOf(self.input()) !== -1))
                return true;

            return false;
        };
        self.isValueItem = function (item) {
            //if (self.itemType !== "key-obj")
            //    return true;
            var itemJs = ko.toJS(item);
            if (self.type === "multi") {
                if (!_h.any(self.values()))
                    return false;
                if (self.values().indexOf(itemJs.value) !== -1)
                    return true;
            } else {
                if (_h.isNullOrEmpty(self.value()))
                    return false;
                if (itemJs.value == self.value())
                    return true;
            }
            return false;
        };
        self.isNumber = function (val) {
            try {
                var test = val.toString();
                var a = parseInt(test);
                var afterParse = a.toString();
                if (afterParse.length <= 0)
                    return false;
                if (afterParse.length === test.length)
                    return true;
                else {
                    var backZero = _h.countBackNumberZero(test);
                    if (test.length - (afterParse.length + backZero) === 0) {
                        return true;
                    } else {
                        return false;
                    }
                }
            } catch (e) {
                return false;
            }
        };
        self.isEmpty = function (val) {
            if (val === null || val === undefined || val === "" || val.length === 0) {
                return true;
            } else {
                if (self.type === "multi")
                    return false;
                var list = ko.isObservable(self.list) ? self.list() : self.list;
                var item, res = true;
                if (!self.itemType) {
                    if (list.length === 0) {
                        self.showMenu(false);
                        return true;
                    }

                    for (var i = 0; i < list.length; i++) {
                        item = ko.toJS(list[i]);
                        if (String(item.value) === String(val))
                            res = false;
                    }
                } else {
                    var keys = Object.keys(list);
                    if (keys.length === 0) {
                        self.showMenu(false);
                        return true;
                    }
                    for (var k = 0; k < keys.length; k++) {
                        item = list[keys[k]];
                        item = ko.toJS(item);
                        if (String(item.value) === String(val))
                            res = false;
                    }
                }

                return res;
            }
        };
        self.reset = function () {
            // todo
        };
        self.shortName = function (name) {
            var div = $("#" + self.id).prev();
            var width = div.width() - 20;
            if (width < 0) {
                self.reset();
                name = ko.isObservable(name) ? name() : name;
                return name;
            }
            name = ko.isObservable(name) ? name() : name;
            if (name !== null && name !== undefined) {
                var res = (name.length * 6.88) > width;
                if (!res)
                    return name;
                return name.substr(0, 22) + "...";
            }
            return "";
        };
        self.getTitle = function (name) {
            var div = $("#" + self.id).prev();
            var width = div.width() - 20;
            if (width < 0) {
                self.reset();
                name = ko.isObservable(name) ? name() : name;
                return name;
            }
            name = ko.isObservable(name) ? name() : name;
            if (name !== null && name !== undefined) {
                var res = (name.length * 6.88) > width;
                if (!res)
                    return "";
                return name;
            }
            return "";
        };
        self.buildList = function () {
            var ul = document.getElementById(self.id);
            if (!ul)
                return;
            ul.innerHTML = "";
            if (self.params.optionsListVar) {
                self.list = self.parentForm[self.params.optionsListVar];
            }
            var item, li, html, span;
            var list = ko.isObservable(self.list) ? self.list() : self.list;
            if (!self.itemType) {
                if (list.length === 0) {
                    self.showMenu(false);
                    return;
                }
                var groupVal = undefined;
                for (var i = 0; i < list.length; i++) {
                    item = ko.toJS(list[i]);
                    if (self.groupBy) {
                        if (groupVal === undefined || item[self.groupBy] !== groupVal) {
                            groupVal = item[self.groupBy];
                            var groupElement = _hh.createElement("li", ul);
                            _hh.setClassName(groupElement, "autocom-group");
                            var values = window[self.groupBy + "s"];
                            if (values && values.length) {
                                groupElement.innerText = _h
                                    .getEnumText(values, item[self.groupBy]);
                            } else {
                                groupElement.innerText = item[self.groupBy];
                            }
                        }
                    }
                    if (self.isShowItem(item)) {
                        li = _hh.createElement("li", ul);
                        li.setAttribute("data-value", item.value);
                        _hh.setClassName(li, "autocom-li");
                        if (self.renderFunc) {
                            html = self.renderFunc(item);
                        }
                        if (!_h.isNullOrEmpty(html) && html !== "")
                            _hh.setInnerHtml(li, html);
                        else {
                            span = _hh.createElement("span", li);
                            _hh.setClassName(span, "autocom-span");
                            _hh.setInnerHtml(span, item.text);
                        }
                        li.onclick = function (ev) {
                            var val = this.getAttribute("data-value");
                            var isRemoveLabel = ev.target.classList.contains("remove-tag");
                            if (isRemoveLabel) {
                                self.removeTag({
                                    text: val,
                                    value: val
                                });
                            }
                            else {
                                var text = this.innerText;
                                if (self.tagManager) {
                                    text = text.replace('\n', '').replace('حذف', '');
                                } else {
                                    if (self.isNumber(val))
                                        val = Number(val);
                                }
                                self.onSelectItem({
                                    text: text,
                                    value: val
                                });
                            }
                        };
                    }
                }
            } else {
                var keys = Object.keys(list);
                for (var k = 0; k < keys.length; k++) {
                    item = list[keys[k]];
                    item = ko.toJS(item);
                    if (self.isShowItem(item)) {
                        li = _hh.createElement("li", ul);
                        li.setAttribute("data-value", item.value);
                        _hh.setClassName(li, "autocom-li");
                        if (self.renderFunc) {
                            html = self.renderFunc(item);
                        }
                        if (!_h.isNullOrEmpty(html) && html !== "")
                            _hh.setInnerHtml(li, html);
                        else {
                            span = _hh.createElement("span", li);
                            _hh.setClassName(span, "autocom-span");
                            _hh.setInnerHtml(span, item.text);
                        }
                        li.onclick = function () {
                            var val = this.getAttribute("data-value");
                            if (!self.tagManager) {
                                if (self.isNumber(val))
                                    val = Number(val);
                            }
                            self.onSelectItem({
                                text: this.innerText,
                                value: val
                            });
                        };
                    }
                }
            }
            _h.fixItemHeight(self.id);
            if (ul.childNodes.length === 0) {
                self.showMenu(false);
            }
            self.calculateOpenListLoc();
        };
        self.calculateOpenListLoc = function () {
            var ul = $("#" + self.id);
            if (ul.length > 0) {
                ul.css('top', "");
                ul.css('bottom', "");
                var ulHeight = ul.height();
                var pageHeight = $("body").height();
                var viewportOffset = ul.get(0).getBoundingClientRect();
                var rest = pageHeight - viewportOffset.top;
                if (rest < ulHeight) {
                    var ulTop = Number(ul.css('top').replace("px", ""));
                    var newTop = ulTop - ulHeight - 8;
                    ul.css('top', newTop + "px");
                } else {
                    ul.css('top', "unset");
                    ul.css('bottom', "-" + ulHeight + "px");
                }
            }

        }
        self.refreshData = function () {
            self.refreshFunc();
        }
        setTimeout(function () {
            self.adjustInputSize();
        }, 300);
    },
    template: "<!-- ko template: { name: 'select-component-t' } --><!-- /ko -->"

});

var periodCustomItem = [
    "groupPeriod",
    "sourcePeriodId",
    "calculationPeriodId"
];