"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var focus_1 = require("@dojo/framework/core/middleware/focus");
var i18n_1 = require("@dojo/framework/core/middleware/i18n");
var icache_1 = require("@dojo/framework/core/middleware/icache");
var resources_1 = require("@dojo/framework/core/middleware/resources");
var util_1 = require("@dojo/framework/core/util");
var vdom_1 = require("@dojo/framework/core/vdom");
var util_2 = require("../common/util");
var helper_text_1 = require("../helper-text");
var icon_1 = require("../icon");
var label_1 = require("../label");
var list_1 = require("../list");
var theme_1 = require("../middleware/theme");
var trigger_popup_1 = require("../trigger-popup");
var listCss = require("../theme/default/list.m.css");
var labelCss = require("../theme/default/label.m.css");
var iconCss = require("../theme/default/icon.m.css");
var css = require("../theme/default/select.m.css");
var Select_1 = require("./nls/Select");
var loading_indicator_1 = require("../loading-indicator");
var array_1 = require("@dojo/framework/shim/array");
var icache = icache_1.createICacheMiddleware();
var factory = vdom_1.create({
    icache: icache,
    focus: focus_1.focus,
    theme: theme_1.default,
    i18n: i18n_1.i18n,
    resource: resources_1.createResourceMiddleware()
})
    .properties()
    .children();
exports.Select = factory(function Select(_a) {
    var children = _a.children, properties = _a.properties, _b = _a.middleware, icache = _b.icache, focus = _b.focus, theme = _b.theme, i18n = _b.i18n, resource = _b.resource;
    var _c = properties(), classes = _c.classes, variant = _c.variant, themeProp = _c.theme, disabled = _c.disabled, helperText = _c.helperText, initialValue = _c.initialValue, _d = _c.itemsInView, itemsInView = _d === void 0 ? 6 : _d, onValidate = _c.onValidate, onValue = _c.onValue, _e = _c.placeholder, placeholder = _e === void 0 ? '' : _e, position = _c.position, required = _c.required, name = _c.name, _f = _c.resource, template = _f.template, _g = _f.options, options = _g === void 0 ? resource.createOptions(function (curr, next) { return (tslib_1.__assign({}, curr, next)); }) : _g;
    var _h = resource.template(template), get = _h.get, read = _h.template.read;
    var _j = tslib_1.__read(children(), 1), _k = _j[0], _l = _k === void 0 ? { items: undefined, label: undefined } : _k, items = _l.items, label = _l.label;
    var value = properties().value;
    if (value === undefined) {
        if (initialValue !== undefined && initialValue !== icache.get('initial')) {
            icache.set('initial', initialValue);
            icache.set('value', initialValue);
        }
        value = icache.get('value');
    }
    var menuId = icache.getOrSet('menuId', util_1.uuid());
    var triggerId = icache.getOrSet('triggerId', util_1.uuid());
    var focusNode = icache.getOrSet('focusNode', 'trigger');
    var shouldFocus = focus.shouldFocus();
    var themedCss = theme.classes(css);
    var valid = icache.get('valid');
    var dirty = icache.get('dirty');
    var messages = i18n.localize(Select_1.default).messages;
    var expanded = icache.get('expanded');
    var _m = get(options(), { read: read, meta: true }), _o = _m.meta, total = _o.total, status = _o.status, data = _m.data;
    if (required && (dirty || value !== undefined)) {
        var isValid = value !== undefined;
        if (isValid !== valid) {
            icache.set('valid', isValid);
            valid = isValid;
            onValidate && onValidate(isValid);
        }
    }
    var valueOption;
    if (value && data) {
        var found = array_1.find(data, function (item) {
            return Boolean(item.value && item.value.value === value);
        });
        if (found) {
            valueOption = found.value;
        }
        else {
            var items_1 = get(options({ query: { value: value } }), { read: read });
            if (items_1 && items_1.length > 0 && items_1[0].value === value) {
                valueOption = items_1[0];
            }
        }
    }
    value = valueOption ? valueOption.value : undefined;
    return (vdom_1.tsx("div", { classes: [
            theme.variant(),
            themedCss.root,
            disabled && themedCss.disabled,
            valid === true && themedCss.valid,
            valid === false && themedCss.invalid,
            shouldFocus === true && themedCss.focused,
            expanded && themedCss.expanded
        ], key: "root" },
        label && (vdom_1.tsx(label_1.default, { theme: theme.compose(labelCss, css, 'label'), classes: classes, variant: variant, disabled: disabled, forId: triggerId, valid: valid, required: required, active: !!(value || icache.get('expanded')), focused: shouldFocus }, label)),
        vdom_1.tsx(trigger_popup_1.default, { key: "popup", onOpen: function () {
                icache.set('expanded', true);
            }, onClose: function () {
                icache.set('expanded', false);
                if (!dirty) {
                    icache.set('dirty', true);
                }
            }, position: position, theme: themeProp, classes: classes, variant: variant }, {
            trigger: function (toggleOpen) {
                function openMenu() {
                    if (!disabled) {
                        icache.set('focusNode', 'menu');
                        focus.focus();
                        toggleOpen();
                    }
                }
                return (vdom_1.tsx("button", { name: name, value: value, focus: function () { return focusNode === 'trigger' && shouldFocus; }, "aria-controls": menuId, "aria-haspopup": "listbox", "aria-expanded": icache.getOrSet('expanded', false) ? 'true' : 'false', key: "trigger", type: "button", id: triggerId, disabled: disabled, classes: themedCss.trigger, onclick: openMenu, onkeydown: function (event) {
                        if (event.which === util_2.Keys.Down ||
                            event.which === util_2.Keys.Space ||
                            event.which === util_2.Keys.Enter) {
                            event.preventDefault();
                            openMenu();
                        }
                    } },
                    vdom_1.tsx("span", { classes: [themedCss.value, expanded && themedCss.valueExpanded] }, (valueOption && valueOption.label) || (vdom_1.tsx("span", { classes: themedCss.placeholder }, placeholder))),
                    vdom_1.tsx("span", { classes: themedCss.arrow },
                        vdom_1.tsx(icon_1.default, { type: "downIcon", theme: theme.compose(iconCss, css, 'icon'), classes: classes, variant: variant }))));
            },
            content: function (close) {
                function closeMenu() {
                    icache.set('focusNode', 'trigger');
                    close();
                }
                return total === undefined && status === 'reading' ? (vdom_1.tsx(loading_indicator_1.default, { key: "loading", theme: themeProp, variant: variant, classes: classes })) : (vdom_1.tsx("div", { key: "menu-wrapper", classes: themedCss.menuWrapper },
                    vdom_1.tsx(list_1.List, { key: "menu", height: "auto", focus: function () { return focusNode === 'menu' && shouldFocus; }, resource: resource({ template: template, options: options }), onValue: function (value) {
                            focus.focus();
                            closeMenu();
                            value.value !== icache.get('value') &&
                                icache.set('value', value.value);
                            onValue(value);
                        }, onRequestClose: closeMenu, onBlur: closeMenu, initialValue: value, itemsInView: itemsInView, theme: theme.compose(listCss, css, 'menu'), classes: classes, variant: variant, widgetId: menuId }, items)));
            }
        }),
        vdom_1.tsx(helper_text_1.default, { key: "helperText", text: valid === false ? messages.requiredMessage : helperText, valid: valid, classes: classes, variant: variant, theme: themeProp })));
});
exports.default = exports.Select;

/*# sourceMappingURL=index.js.map*/