export default class ASpinButton extends window.AObject {
    constructor(ev) {
        super();
        this.el = ev;
        if (ev instanceof NodeList) {
            this.el.forEach((e) => {
                this.init(e);
            });
        } else {
            this.init(ev);
        }

    }
    init(e) {
        var pa = e.closest(".input-custom");
        var m = pa.querySelector(".minus");
        var p = pa.querySelector(".plus");
        var f = function (evt) {
            this.MinusEvent.call(this, evt, e);
        }.bind(this);
        m.addEventListener("click", f, false);
        var f1 = function (evt) {
            this.PlusEvent.call(this, evt, e);
        }.bind(this);
        p.addEventListener("click", f1, false);
        var f2 = function (evt) {
            this.InputChange.call(this, evt);
        }.bind(this);
        e.addEventListener("keyup", f2, false);
        e.value = e.getAttribute("default-value");
    }
    MinusEvent(e, inp) {
        inp.focus();
        if (inp.value == "") {
            inp.value = inp.getAttribute("default-value").toLocaleString("us-US");
            return;
        }
        var v = parseFloat(inp.value.replace(/[,]/g, ''));
        var step = parseFloat(inp.getAttribute("step-value"));
        var min = parseFloat(inp.getAttribute("min-value"));
        if ((v - step) < min) {
            return;
        } else {
            inp.value = (v - step).toLocaleString("us-US");
        }
    }
    PlusEvent(e, inp) {
        inp.focus();
        if (inp.value == "") {
            inp.value = inp.getAttribute("default-value").toLocaleString("us-US");
            return;
        }
        var v = parseFloat(inp.value.replace(/[,]/g, ''));
        var step = parseFloat(inp.getAttribute("step-value"));
        var max = parseFloat(inp.getAttribute("max-value"));
        if ((v + step) > max) {
            return;
        } else {
            inp.value = (v + step).toLocaleString("us-US");
        }
    }
    InputChange(e) {
        var selection = window.getSelection().toString();
        if (selection !== '') {
            return;
        }
        var arr = [38, 40, 37, 39];
        if (e.currentTarget.hasAttribute("floating-point")) arr.push(190);
        if (arr.includes(e.keyCode)) {
            return;
        }
        var step = parseFloat(e.currentTarget.getAttribute("step-value"));
        var max = parseFloat(e.currentTarget.getAttribute("max-value"));
        var min = parseFloat(e.currentTarget.getAttribute("min-value"));
        var input = e.currentTarget.value;
        var input = input.replace(/[^\d\.\-]+/g, "");
        input = parseFloat(input);
        if (input > max) {
            input = max;
        }
        if (input < min) {
            input = min
        }
        e.currentTarget.value = (e.currentTarget.value == "") ? "" : input.toLocaleString("us-US");

    }
}