'use strict';

oml.ui.statusbar = function() {

    var ui = oml.user.ui,

        data = {
            loading: true,
            selected: {items: 0, size: 0},
            total: {items: 0, size: 0},
        },

        $status = Ox.Element()
            .css({
                margin: '2px 4px',
                fontSize: '9px',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
            }),

        that = Ox.Bar({size: 16})
            .css({textAlign: 'center'})
            .append($status)
            .bindEvent({
                oml_find: function(data) {
                    that.set('loading', true);
                },
                oml_listselection: function(data) {
                    if (ui.listSelection.length) {
                        oml.api.find({
                            query: {
                                conditions: ui.listSelection.map(function(id) {
                                    return {
                                        key: 'id',
                                        operator: '==',
                                        value: id
                                    };
                                }),
                                operator: '|'
                            }
                        }, function(result) {
                            that.set('selected', result.data);
                        });
                    } else {
                        that.set('selected', {items: 0, size: 0});
                    }
                }
            });

    that.set = function(key, value) {
        var hasSelection;
        data[key] = value;
        if (key != 'loading') {
            data.loading = false;
        }
        hasSelection = data.selected.items
            && data.selected.items < data.total.items;
        $status.html(data.loading ? Ox._('Loading...') : ((
            hasSelection ? Ox.formatNumber(data.selected.items) + ' of ' : ''
        ) + Ox.toTitleCase(Ox.formatCount(data.total.items, 'book')) + (
            data.total.items ? ', ' + (
                hasSelection ? Ox.formatValue(data.selected.size, 'B') + ' of ' : ''
            ) + Ox.formatValue(data.total.size, 'B') : ''
        )));
    };

    return that;

};