"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ChoiceContainer_1 = require("../renderable/choice/ChoiceContainer");
var ChoiceAggregator_1 = require("../renderable/submit/ChoiceAggregator");
var SubmitState_1 = require("../renderable/submit/SubmitState");
var node_1 = require("./node");
var node_2 = require("./node");
var InputContainer = /** @class */ (function () {
    function InputContainer() {
    }
    /**
     * Returns a {@link Promise} containing the attributes of the input elements
     *
     * @param container: the parent form element
     * @param submit: the submit button element
     */
    InputContainer.getAll = function (container, submit) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var _a;
            var attributes = {};
            var state = SubmitState_1.SubmitState.ALLOWED;
            container.querySelectorAll(_this.ELEMENTS_AS_STRING).forEach(function (e) {
                var newState = InputContainer.addValuesToAttributes(e, attributes);
                console.debug("State is " + newState);
                if (state == SubmitState_1.SubmitState.ALLOWED) {
                    state = newState;
                }
            });
            var choiceContainers = container.querySelectorAll("div." + ChoiceContainer_1.ChoiceContainer.CSS_BASE_CLASS);
            if (choiceContainers.length > 0) {
                var result = ChoiceAggregator_1.ChoiceAggregator.aggregate(choiceContainers);
                if (result.state === SubmitState_1.SubmitState.SUBMIT_REQUIRED_ERROR) {
                    state = SubmitState_1.SubmitState.SUBMIT_REQUIRED_ERROR;
                }
                else {
                    Object.assign(attributes, result.attributes);
                }
            }
            else {
                container.querySelectorAll("input[type='checkbox']").forEach(function (checkbox) {
                    InputContainer.addValuesToAttributes(checkbox, attributes);
                });
            }
            container.querySelectorAll(".lto-basket").forEach(function (basket) {
                var required = _this.getNormalOrDataAttribute(basket, "required");
                if (required && required === "true") {
                    var basketName = _this.getNormalOrDataAttribute(basket, "name");
                    if (!basketName || !attributes[basketName]) {
                        state = SubmitState_1.SubmitState.SUBMIT_REQUIRED_ERROR;
                    }
                }
            });
            container.querySelectorAll(".lto-submit-error").forEach(function (e) { return e.remove(); });
            submit.classList.remove("lto-error");
            Object.keys(SubmitState_1.SubmitState).map(function (key) { return SubmitState_1.SubmitState[key]; }).forEach(function (value) {
                submit.classList.remove(value);
            });
            if (state == SubmitState_1.SubmitState.ALLOWED) {
                // workaround to keep existing data structure
                if (container.name) {
                    var array = [];
                    for (var e in attributes) {
                        array.push((_a = {}, _a[e] = attributes[e], _a));
                    }
                    container.setAttribute("data-value", JSON.stringify(array));
                    attributes = {};
                    InputContainer.addValuesToAttributes(container, attributes);
                }
                container.classList.remove("lto-error");
            }
            else {
                if (!container.classList.contains("lto-error")) {
                    container.classList.add("lto-error");
                }
                var span = node_1.default("span");
                span.addClasses("lto-submit-error", "lto-" + state);
                submit.classList.add("lto-error", "lto-" + state);
                submit.parentElement.appendChild(span.unwrap());
                reject("not allowed");
            }
            resolve(attributes);
        });
    };
    /**
     * Adds the value of the element to the attributes
     *
     * @param element
     * @param attributes
     */
    InputContainer.addValuesToAttributes = function (element, attributes) {
        var name = InputContainer.getNormalOrDataAttribute(element, "name") || "undefined";
        var value = InputContainer.getNormalOrDataAttribute(element, "value");
        var required = InputContainer.getRequiredAttribute(element);
        // element value is required but empty
        if (required && !value) {
            if (!element.classList.contains("lto-error"))
                element.classList.add("lto-error");
            console.warn("Input is required");
            return SubmitState_1.SubmitState.SUBMIT_REQUIRED_ERROR;
        }
        // element value is not valid
        if (element instanceof HTMLInputElement && !element.checkValidity()) {
            console.warn("Input is not valid");
            if (!element.classList.contains("lto-error"))
                element.classList.add("lto-error");
            return SubmitState_1.SubmitState.SUBMIT_VALIDATION_ERROR;
        }
        if (value) {
            var preparedValue = value;
            try {
                preparedValue = JSON.parse(value);
            }
            catch (e) {
                console.debug("Unable to parse value as JSON for element " + element + ": " + e);
            }
            var basket = node_2.default(element).getParentByClass("lto-basket");
            if (basket) {
                var basketName = this.getNormalOrDataAttribute(basket.unwrap(), "name");
                basketName && this.createBasket(basketName, attributes, name, preparedValue);
            }
            else {
                attributes[name] !== undefined ?
                    attributes[name].push(preparedValue) :
                    attributes[name] = [preparedValue];
            }
        }
        element.classList.remove("lto-error");
        return SubmitState_1.SubmitState.ALLOWED;
    };
    InputContainer.createBasket = function (basketName, attributes, name, value) {
        var _a, _b, _c, _d;
        var contextBasket = attributes[basketName];
        if (contextBasket !== undefined) {
            var curBasketItem = contextBasket[contextBasket.length - 1];
            if (!curBasketItem.basketItem.hasOwnProperty(name)) {
                curBasketItem.basketItem[name] = value;
            }
            else {
                contextBasket.push((_a = {}, _a['basketItem'] = (_b = {}, _b[name] = value, _b), _a));
            }
        }
        else {
            attributes[basketName] = [(_c = {}, _c['basketItem'] = (_d = {}, _d[name] = value, _d), _c)];
        }
    };
    InputContainer.getNormalOrDataAttribute = function (element, name) {
        if (element.hasAttribute(name)) {
            return element.getAttribute(name);
        }
        if (element.hasAttribute("data-" + name)) {
            return element.getAttribute("data-" + name);
        }
        return null;
    };
    InputContainer.getRequiredAttribute = function (element) {
        var requiredAttribute = "required";
        if (element.hasAttribute(requiredAttribute)) {
            return true;
        }
        if (element.hasAttribute("data-required")) {
            return element.getAttribute("data-" + requiredAttribute) == "true";
        }
        return false;
    };
    InputContainer.setRequiredAttribute = function (element, required) {
        if (!required) {
            return;
        }
        if (required == "true" || required == true) {
            if (element.tagName.toLowerCase() == "input" || element.tagName.toLowerCase() == "textarea") {
                element.setAttribute("required", "required");
                return;
            }
            element.setAttribute("data-required", "true");
        }
    };
    InputContainer.ELEMENTS = [
        'div.lto-camera',
        'div.lto-code-reader',
        'div.lto-drop-area',
        'div.lto-map',
        'div.lto-reel',
        'div.lto-trigger',
        'input.lto-email',
        'input.lto-phone',
        'input.lto-slider',
        'input.lto-spinner',
        'input.lto-text',
        'textarea.lto-textarea',
    ];
    InputContainer.ELEMENTS_AS_STRING = InputContainer.ELEMENTS.join(",");
    return InputContainer;
}());
exports.InputContainer = InputContainer;
//# sourceMappingURL=InputContainer.js.map