"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var vdom_1 = require("@dojo/framework/core/vdom");
var icache_1 = require("@dojo/framework/core/middleware/icache");
var i18n_1 = require("@dojo/framework/core/middleware/i18n");
var theme_1 = require("../middleware/theme");
var dimensions_1 = require("@dojo/framework/core/middleware/dimensions");
var resize_1 = require("@dojo/framework/core/middleware/resize");
var resources_1 = require("@dojo/framework/core/middleware/resources");
var global_1 = require("@dojo/framework/shim/global");
var icon_1 = require("../icon");
var select_1 = require("../select");
var Pagination_1 = require("./nls/Pagination");
var css = require("../theme/default/pagination.m.css");
var pageSizesTemplate = resources_1.createResourceTemplate('value');
function getRenderedWidth(dnode, wrapperClass) {
    if (dnode === undefined) {
        return 0;
    }
    var r = vdom_1.default(function () { return dnode; });
    var div = global_1.default.document.createElement('div');
    div.className = wrapperClass || '';
    div.style.position = 'absolute';
    global_1.default.document.body.appendChild(div);
    r.mount({ domNode: div, sync: true });
    var dimensions = div.getBoundingClientRect();
    global_1.default.document.body.removeChild(div);
    return dimensions.width;
}
var icache = icache_1.createICacheMiddleware();
var resource = resources_1.createResourceMiddleware();
var factory = vdom_1.create({
    theme: theme_1.default,
    icache: icache,
    i18n: i18n_1.default,
    dimensions: dimensions_1.default,
    resize: resize_1.default,
    diffProperty: vdom_1.diffProperty,
    resource: resource
}).properties();
exports.default = factory(function Pagination(_a) {
    var id = _a.id, _b = _a.middleware, theme = _b.theme, icache = _b.icache, i18n = _b.i18n, dimensions = _b.dimensions, resize = _b.resize, diffProperty = _b.diffProperty, resource = _b.resource, properties = _a.properties;
    diffProperty('theme', function (current, next) {
        if (current !== next) {
            icache.delete('fixedWidth', false);
            icache.delete('siblingWidth', false);
        }
    });
    resize.get('root');
    var _c = properties(), initialPage = _c.initialPage, initialPageSize = _c.initialPageSize, onPage = _c.onPage, onPageSize = _c.onPageSize, pageSizes = _c.pageSizes, siblingCount = _c.siblingCount, total = _c.total;
    var classes = theme.classes(css);
    var messages = i18n.localize(Pagination_1.default).messages;
    var _d = properties(), page = _d.page, pageSize = _d.pageSize;
    if (page === undefined &&
        initialPage !== undefined &&
        initialPage !== icache.get('initialPage')) {
        icache.set('initialPage', initialPage);
        icache.set('currentPage', initialPage);
    }
    var currentPage = page === undefined ? icache.getOrSet('currentPage', 1) : page;
    if (pageSize === undefined &&
        initialPageSize !== undefined &&
        initialPageSize !== icache.get('initialPageSize')) {
        icache.set('initialPageSize', initialPageSize);
        icache.set('pageSize', initialPageSize);
    }
    var currentPageSize = pageSize === undefined ? icache.getOrSet('pageSize', 10) : pageSize;
    if (pageSizes !== undefined && pageSizes !== icache.get('pageSizes')) {
        icache.set('pageSizes', pageSizes);
    }
    var showPrev = currentPage > 1;
    var prevLink = (vdom_1.tsx("button", { type: "button", key: "prev", classes: [classes.prev, classes.link], onclick: function (e) {
            e.stopPropagation();
            icache.set('currentPage', currentPage - 1);
            onPage && onPage(currentPage - 1);
        } },
        vdom_1.tsx("div", { classes: classes.icon },
            vdom_1.tsx(icon_1.default, { type: "leftIcon" })),
        vdom_1.tsx("div", { classes: classes.label }, messages.previous)));
    var showNext = currentPage < total;
    var nextLink = (vdom_1.tsx("button", { type: "button", key: "next", classes: [classes.next, classes.link], onclick: function (e) {
            e.stopPropagation();
            icache.set('currentPage', currentPage + 1);
            onPage && onPage(currentPage + 1);
        } },
        vdom_1.tsx("div", { classes: classes.icon },
            vdom_1.tsx(icon_1.default, { type: "rightIcon" })),
        vdom_1.tsx("div", { classes: classes.label }, messages.next)));
    var leadingSiblings = [];
    var trailingSiblings = [];
    var containerWidth = dimensions.get('links').size.width;
    if (containerWidth) {
        var fixedWidth = icache.getOrSet('fixedWidth', getRenderedWidth(prevLink, theme.variant()) +
            getRenderedWidth(nextLink, theme.variant()) +
            getRenderedWidth(vdom_1.tsx("div", { classes: classes.currentPage }, total.toString()), theme.variant()));
        var siblingWidth = icache.getOrSet('siblingWidth', getRenderedWidth(vdom_1.tsx("button", { classes: [classes.numberedLink, classes.link] }, total.toString()), theme.variant()));
        var availableSpace = (containerWidth - fixedWidth) / siblingWidth;
        var maxLeading = siblingCount ? Math.min(siblingCount, currentPage - 1) : currentPage - 1;
        var maxTrailing = siblingCount
            ? Math.min(siblingCount, total - currentPage)
            : total - currentPage;
        var _loop_1 = function (i) {
            var showLeading = i <= maxLeading;
            var showTrailing = i <= maxTrailing;
            var spaceNeeded = 0;
            if (showLeading) {
                spaceNeeded++;
            }
            if (showTrailing) {
                spaceNeeded++;
            }
            if (availableSpace >= spaceNeeded) {
                var leadingPageNumber_1 = currentPage - i;
                var trailingPageNumber_1 = currentPage + i;
                if (showLeading) {
                    leadingSiblings.unshift(vdom_1.tsx("button", { type: "button", key: "numberedLink-" + leadingPageNumber_1, classes: [classes.numberedLink, classes.link], onclick: function (e) {
                            e.stopPropagation();
                            icache.set('currentPage', leadingPageNumber_1);
                            onPage && onPage(leadingPageNumber_1);
                        } }, leadingPageNumber_1.toString()));
                }
                if (showTrailing) {
                    trailingSiblings.push(vdom_1.tsx("button", { type: "button", key: "numberedLink-" + trailingPageNumber_1, classes: [classes.numberedLink, classes.link], onclick: function (e) {
                            e.stopPropagation();
                            icache.set('currentPage', trailingPageNumber_1);
                            onPage && onPage(trailingPageNumber_1);
                        } }, trailingPageNumber_1.toString()));
                }
                availableSpace -= spaceNeeded;
            }
            else {
                return "break";
            }
        };
        for (var i = 1; i <= Math.max(maxLeading, maxTrailing); i++) {
            var state_1 = _loop_1(i);
            if (state_1 === "break")
                break;
        }
    }
    return (total > 1 && (vdom_1.tsx("div", { key: "root", classes: [theme.variant(), classes.root] },
        vdom_1.tsx("div", { key: "links", classes: classes.linksWrapper, styles: {
                opacity: containerWidth ? '1' : '0'
            } },
            showPrev && prevLink,
            leadingSiblings,
            vdom_1.tsx("div", { key: "current", classes: classes.currentPage }, currentPage.toString()),
            trailingSiblings,
            showNext && nextLink),
        pageSizes && pageSizes.length > 0 && (vdom_1.tsx("div", { classes: classes.selectWrapper },
            vdom_1.tsx(select_1.default, { key: "page-size-select", initialValue: pageSize === undefined ? currentPageSize.toString() : undefined, value: pageSize === undefined ? undefined : pageSize.toString(), resource: resource({
                    template: pageSizesTemplate({
                        id: id,
                        data: pageSizes.map(function (ps) { return ({
                            value: "" + ps,
                            label: "" + ps
                        }); })
                    })
                }), onValue: function (value) {
                    onPageSize && onPageSize(parseInt(value.value, 10));
                } }))))));
});

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