Ext.define("Portfolio.pd.manager.component.field.ValuePicker", {

    xtype: "pd-manager-field-valuepicker",

    extend: "Ext.form.field.Picker",

    alias: [
        "widget.pd-manager-field-valuepicker"
    ],


    editable: false,

    hideTrigger: false,

    pickerOffset: [0, 0],

    matchFieldWidth: false,

    listeners: {
        focus: {
            fn: function(i_field) {
                i_field.expand();
            }
        }
    },

    config: {
        grid: null
    },

    initComponent: function() {

        var i_self = this;
        i_self.callParent(arguments);
    },

    updateValues: function() {

        var i_self = this;
        var i_grid = i_self.getGrid();
        var i_store = i_grid.getStore();

        var a_records = i_store.getRange();
        
        var a_return = [];

        Ext.Array.each(a_records, function(i_record) {

            a_return.push({
                text: i_record.get("text"),
                key: i_record.get("key")
            });

        });

        i_self.setRawValue(i_self.valueToRaw(a_return));
    },

    createPicker: function() {

        var i_self = this;

        var i_itemStore = Ext.create("Ext.data.Store", {
            fields: [
                {
                    name: "text",
                    type: "auto"
                },
                {
                    name: "key",
                    type: "auto"
                },
                {
                    name: "active",
                    type: "boolean",
                    defaultValue: true
                }
            ],
            idProperty: "key",
            data: []
        });

        var i_grid = Ext.widget("grid", {
            header: {
                cls: "x-window-header-default",
                title: {
                    style: {
                        color: "white"
                    }
                }
            },
            tools: [{
                type: "plus",
                tooltip: ip2.i18n({
                    da: "Tilføj række",
                    en: "Add row"
                }),
                handler: function() {
                    var i_plugin = i_grid.getPlugin("c-edit");

                    var i_model = i_itemStore.getModel();
                    var i_record = i_model.create({});
                    i_itemStore.add(i_record);
                    
                    if (i_plugin) {

                        var n_row = i_itemStore.indexOf(i_record);

                        i_plugin.startEditByPosition({
                            row: n_row,
                            column: 0
                        });
                    }
                }
            }],
            hideHeaders: true,
            viewConfig: {
                plugins: {
                    gridviewdragdrop: {
                        dragText: "Drag and drop to reorganize"
                    }
                },
                getRowClass: function(i_record) {
                    return i_record.get("active") ? "" : "pd-value-picker-row-deactive";
                }
            },
            plugins: [
                {
                    ptype: "cellediting",
                    clicksToEdit: 2,
                    id: "c-edit"
                }
            ],
            store: i_itemStore,
            columns: [
                {
                    dataIndex: "text",
                    header: "Text",
                    editor: {
                        xtype: "textfield"
                    },
                    flex: 1
                },
                {
                    dataIndex: "key",
                    header: "Key",
                    editor: {
                        xtype: "textfield"
                    },
                    flex: 1
                },
                {
                    xtype: "widgetcolumn",
                    align: "right",
                    dataIndex: "action",
                    menuDisabled: true,
                    hideable: false,
                    sortable: false,
                    groupable: false,
                    defaults: {
                        margin: "auto"
                    },
                    widget: {
                        xtype: "button",
                        iconCls: "pd-value-picker-delete pf-options",
                        arrowVisible: true,
                        width: 20,
                        ui: "function-action",
                        menu: {
                            plain: true,
                            items: [
                                {
                                    xtype: "menuitem",
                                    itemId: "item-activate",
                                    text: ip2.i18n({
                                        da: "Aktiver",
                                        en: "Activate"
                                    }),
                                    handler: function (i_item) {
                                        
                                        var i_button  = i_item.up("button");
                                        var i_record = i_button.getWidgetRecord();
                                        i_record.set("active", true);
                                        i_record.commit(true);
                                    }
                                },
                                {
                                    xtype: "menuitem",
                                    itemId: "item-deactivate",
                                    text: ip2.i18n({
                                        da: "Deaktiver",
                                        en: "Deactivate"
                                    }),
                                    handler: function (i_item) {

                                        var i_button  = i_item.up("button");
                                        var i_record = i_button.getWidgetRecord();

                                        i_record.set("active", false);
                                        i_record.commit(true);
                                    }
                                },
                                {
                                    xtype: "menuitem",
                                    itemId: "item-delete",
                                    text: ip2.i18n({
                                        da: "Slet",
                                        en: "Delete"
                                    }),
                                    handler: function (i_item) {

                                        var i_store = i_grid.getStore();

                                        var i_button  = i_item.up("button");
                                        var i_record = i_button.getWidgetRecord();

                                        var n_row = i_store.indexOf(i_record);

                                        var i_view = i_grid.getView();

                                        
                                        if (n_row > 0) {
                                            i_view.focusRow(n_row -1);
                                        }
                                        else {
                                            i_view.focusRow(i_store.getRange().length - 1);
                                        }
                                        
                                        i_store.remove(i_record);
                                    }
                                }
                            ],
                            listeners: {
                                beforeshow: {
                                    fn: function(i_menu) {

                                        var i_button  = i_menu.up("button");
                                        var i_record = i_button.getWidgetRecord();

                                        var b_active = i_record.get("active");

                                        var i_activate = i_menu.getComponent("item-activate");
                                        var i_deactivate = i_menu.getComponent("item-deactivate");

                                        i_activate[b_active ? "disable" : "enable"]();
                                        i_deactivate[b_active ? "enable" : "disable"]();
                                    }
                                }
                            }
                        }   
                    }
                }
            ],
            listeners: {
                afterrender: {
                    fn: function() {

                        var i_header = i_grid.getHeader();
                        var i_titleCmp = i_header.titleCmp;

                        if (i_titleCmp) {
                            i_titleCmp.setText(ip2.i18n({
                                da: "Rediger tekst og nøgle",
                                en: "Edit text and key"
                            }));
                        }
                        
                        i_header.tools.plus.setStyle("margin", "0px 0px 0px -4px");

                        var i_el = i_header.tools.plus.toolEl;

                        i_el.dom.style.setProperty("color", "white", "important");
                    },
                    buffer: 100
                },
                edit: {
                    fn: function(i_editor, i_event) {
                        var i_record = i_event.record;
                        i_record.commit();
                        i_self.updateValues();
                    }
                }
            }
        });

        var i_store = i_grid.getStore();

        i_store.on({
            add: {
                fn: function() {
                    i_self.updateValues();
                },
                buffer: 10
            },
            remove: {
                fn: function() {
                    
                    i_self.updateValues();
                },
                buffer: 10
            }
        });

        var i_picker = Ext.widget("panel", {
            layout: "fit",
            height: 300,
            width: 500,
            pickerField: i_self,
            ownerCt: i_self.ownerCt,
            renderTo: Ext.getBody(),
            floating: true,
            items: [
                i_grid
            ],
            listeners: {
                afterrender: {
                    fn: function() {

                        var a_value = i_self.mixins.field.getValue.call(i_self);
                        i_self.setValue(a_value);
                    },
                    buffer: 100
                },
                show: {
                    fn: function() {

                        var a_value = i_self.mixins.field.getValue.call(i_self);
                        i_self.setValue(a_value);
                    }
                }
            }
        });

        i_self.setGrid(i_grid);

        return i_picker;
    },


    getValue: function() {

        var i_self = this;
        var i_grid = i_self.getGrid();

        var a_return = [];

        if (i_grid) {

            var i_store = i_grid.getStore();
            var a_records = i_store.getRange();

            Ext.Array.each(a_records, function(i_record) {
                a_return.push({
                    text: i_record.get("text"),
                    key: i_record.get("key"),
                    active: i_record.get("active")
                });
            });
        }
        else {
            a_return = i_self.mixins.field.getValue.call(i_self);
        }
        

        return a_return;
    },

    valueToRaw: function(value) {

        return Ext.encode(value, true) || value;
    },

    setValue: function(value) {

        var i_self = this;
        var i_grid = i_self.getGrid();

        if (Ext.isString(value)) {
            value = [
                {
                    text: value,
                    key: value
                }
            ];
        }

        var a_result = [];

        var a_values = Ext.Array.from(value);

        Ext.Array.each(a_values, function(value) {

            var o_value = value;
            
            if (Ext.isString(value)) {
                o_value = {
                    text: value,
                    key: value,
                    active: true
                };

                a_result.push(o_value);
            }
            else {

                o_value = {
                    text: value.text || value.key,
                    key: value.value || value.key,
                    active: value.active
                };

                a_result.push(o_value);
            }
        });

        if (i_grid) {

            var i_store = i_grid.getStore();
            var a_records = i_store.getRange();
            
            var a_add = [];
    
            Ext.Array.each(a_result, function(o_value) {
    
                var i_found = Ext.Array.findBy(a_records, function(i_record) {
                    return i_record.get("key") == o_value.key;
                });
    
                if (!i_found) {
                    a_add.push(o_value);
                }
            });

            if (!Ext.isEmpty(a_add)) {
                i_store.loadRawData(a_add, false);
            }
        }

        i_self.callOverridden([a_result]);
        
        i_self.value = a_result;
		i_self.mixins.field.setValue.call(i_self, a_result);
    }
});