Ext.define("Portfolio.ux.form.field.pd.Picker", {
    
    extend: "Ext.form.field.ComboBox",

    alternateClassName: [
        "Ext.ux.form.field.pd.Picker"
    ],

    alias: [
        "widget.pd-picker"
    ],

    isFormField: false,
    
    editable: true,

    typeAHead: true,

    minChars: 1,

    config: {
        url: "/pd/collection"
    },

    valueField: "name",
    
    displayField: "label",

    initComponent: function() {

        var i_self = this;
        
        Ext.apply(i_self, {
            tpl: i_self.createListTpl(),
            displayTpl: i_self.createDisplayTpl(),
            store: i_self.createStore(),
            listeners: {
                select: {
                    fn: function(i_field, i_record) {
                        i_self.fireEvent("changecollection", i_record.get("name"), i_field.lastValue);
                    }
                }
            }
        });

        i_self.callParent(arguments);

        i_self.enableBubble([
            "changecollection"
        ]);
    },

    createStore: function() {

        var i_self = this;

        var a_data = Portfolio.pd.util.Cache.load(i_self.getUrl());

        var a_filtered = Ext.Array.filter(a_data, function(o_config) {
            return o_config.type == "formCollection" && !o_config.isTemplate;
        });

        var i_store = Ext.create("Ext.data.Store", {
            autoLoad: true,
            fields: [
                {
                    name: "name",
                    type: "auto"
                },
                {
                    name: "label",
                    type: "auto"
                }
            ],
            data: a_filtered
        });

        return i_store;
    },

    createListTpl: function() {

        var i_template = Ext.create("Ext.XTemplate",
            "<tpl for=\".\">",
                "<li role=\"option\" class=\"x-boundlist-item\" style=\"text-overflow: ellipsis; white-space: nowrap; overflow:hidden;\">",
                    "{[this.getValue(values.label)]}",
                "</li>",
            "</tpl>",
            {
                getValue: function(value) {
                    return ip2.i18n(value, value);
                }
            }
        );

        return i_template;
    },

    createDisplayTpl: function() {
        
        var i_self = this;

        var i_tpl = Ext.create("Ext.XTemplate",
			"<tpl for=\".\">",
			"{[typeof values === \"string\" ? values : this.renderer(values.label)]}",
			"<tpl if=\"xindex < xcount\">" + i_self.delimiter + "</tpl>",
			"</tpl>",
			{
				renderer: function(value) {
                    return ip2.i18n(value, value);
                }
			}
		);
		return i_tpl;
    }
});