'use strict';

oml.ui.editDialog = function() {

    var ui = oml.user.ui,
        arrayKeys = [
            'author', 'place', 'publisher', 'language'
        ],
        hasChanged = false,
        ids = ui.listSelection.filter(function(id) {
            return oml.$ui.list.value(id, 'mediastate') == 'available';
        }),
        keys = [
            'title', 'author',
            'publisher', 'place', 'date',
            'series', 'edition', 'language', 'pages',
            'categories', 'isbn', 'description', 'tableofcontents'
        ],
        mixed = ' ',
        separator = '; ',
        tooltip = Ox._('Doubleclick to edit'),

        $info = Ox.Element()
            .addClass('OxSelectable')
            .css({padding: '16px'});

    var that = Ox.Dialog({
            buttons: [
                Ox.Button({
                    style: 'squared',
                    title: Ox._('Done')
                })
                .bindEvent({
                    click: function() {
                        if (!ui.updateResults && hasChanged) {
                            Ox.Request.clearCache();
                            oml.$ui.info.updateElement();
                            oml.reloadLists();
                        }
                        that.close();
                    }
                })
            ],
            closeButton: true,
            content: Ox.LoadingScreen().start(),
            height: 256,
            removeOnClose: true,
            title: Ox._('Edit Metadata for {0}', [
                Ox.formatNumber(ids.length) + ' ' + (
                    ids.length == 1 ? 'Book' : 'Books'
                )
            ]),
            width: 512
        }),

        $updateCheckbox = Ox.Checkbox({
                style: 'squared',
                title: Ox._('Update Results in the Background'),
                value: ui.updateResults
            })
            .css({
                float: 'left',
                margin: '4px'
            })
            .bindEvent({
                change: function(data) {
                    oml.UI.set({updateResults: data.value});
                }
            });

    $($updateCheckbox.find('.OxButton')[0]).css({margin: 0});
    $(that.find('.OxBar')[1]).append($updateCheckbox);

    getMetadata();

    function getMetadata(callback) {
        oml.api.find({
            keys: keys,
            query: {
                conditions: ids.map(function(id) {
                    return {
                        key: 'id',
                        operator: '==',
                        value: id
                    };
                }),
                operator: '|'
            }
        }, function(result) {
            var data = {},
                isMixed = {},
                items = result.data.items;
            keys.forEach(function(key) {
                var isArray = Ox.contains(arrayKeys, key),
                    values = items.map(function(item) {
                        return item[key];
                    });
                if (isArray) {
                    values = values.map(function(value) {
                        return (value || []).join(separator);
                    });
                }
                if (Ox.unique(values).length > 1) {
                    isMixed[key] = true;
                }
                data[key] = isMixed[key] ? null
                    : isArray ? values[0].split(separator)
                    : values[0];
            });
            that.options({
                content: oml.ui.infoView(data, isMixed).bindEvent({
                    change: function() {
                        hasChanged = true;
                    }
                })
            });
        });
    }

    return that;

};