'use strict';

pandora.ui.importDocumentsDialog = function() {

    var dialogHeight = 128 + 16,
        dialogWidth = 512 + 16,
        formWidth = getFormWidth(),

        $button,
        $content = Ox.Element(),
        value,
        $input = [
            Ox.Input({
                type: 'textarea',
                height: 128,
                width: 512
            }).css({
                margin: '8px'
            }).bindEvent({
                change: function(data) {
                    $button.options({disabled: !data.value});
                    value = data.value
                }
            }).appendTo($content),
        ],

        that = Ox.Dialog({
                buttons: [
                    Ox.Button({
                            id: 'cancel',
                            title: Ox._('Cancel')
                        })
                        .bindEvent({
                            click: function() {
                                that.close();
                            }
                        }),
                    $button = Ox.Button({
                            disabled: false,
                            id: 'import',
                            title: Ox._('Import URLs')
                        })
                        .bindEvent({
                            click: importDocuments
                        })
                ],
                closeButton: true,
                content: $content,
                height: dialogHeight,
                removeOnClose: true,
                title: Ox._('Import Documents'),
                width: dialogWidth
            })
            .bindEvent({
                resize: setSize
            });

    function getFormWidth() {
        return dialogWidth - 32 - Ox.UI.SCROLLBAR_SIZE;
    }

    function setSize(data) {
        dialogHeight = data.height;
        dialogWidth = data.width;
        formWidth = getFormWidth();
        $input.forEach(function($element) {
            $element.options({width: formWidth});
        });
    }

    function importDocuments() {
        that.options({content: Ox.LoadingScreen().start()});
        var urls = value.trim().split('\n');
        pandora.api.importDocuments({
            urls: urls
        }, function(result) {
            Ox.Request.clearCache()
            if (result.data.taskId) {
                pandora.wait(result.data.taskId, function(result) {
                    that.close();
                    if (pandora.user.ui.section == 'documents' && !pandora.user.ui.document.length) {
                        pandora.$ui.list.reloadList()
                    } else {
                        pandora.URL.push('/documents/grid/created')
                    }
                })
            } else {
                that.options({content: 'Failed'});
            }
        })
    }
    return that;
};