'use strict';

oml.ui.selectFolder = function(options, self) {
    var inputOptions = {
            style: options.style,
            placeholder: options.placeholder,
            width: options.width - options.labelWidth - 4,
            value: options.title,
            autocomplete: function(value, callback) {
                oml.api.autocompleteFolder({path: value}, function(result) {
                    callback(result.data.items);
                });
            },
            autocompleteSelect: true,
            changeOnKeypress: true,
        },
        buttonOptions = {
            overlap: 'left',
            tooltip: Ox._('Select Folder'),
            style: options.style,
            title: 'directory',
            type: 'image'
        };
    var $button = Ox.Button(buttonOptions).bindEvent({
            click: function(event) {
                oml.api.selectFolder({
                    base: $input.value()
                }, function(result) {
                    if (result.data.path) {
                        $input.value(result.data.path);
                        that.triggerEvent('change', result.data.path);
                    }
                })
            }
        }).css({
            'padding-left': '4px'
        }),
        $input = Ox.Input(inputOptions),
        that = Ox.FormElementGroup({
            id: options.id,
            elements: [
                Ox.Label({
                    style: options.style,
                    textAlign: 'right',
                    overlap: 'right',
                    title: options.label,
                    width: options.labelWidth
                }),
                $input,
                $button
            ],
        }, self);

    that.value = function() {
        return $input.value()
    }

    if (options.title && options.title != '...') {
        $button.value(options.title)
    }
    return that;
}