Ext.define("Portfolio.pd.manager.component.grid.view.Form", {
    
    extend: "Ext.grid.Panel",

    alias: [
        "widget.pd-manager-grid-form"
    ],

    requires: [
        "Portfolio.pd.manager.component.grid.model.Form"
    ],

    viewConfig: {
        getRowClass: function(i_record) {
            return i_record.get("active") ? "" : "pd-grid-row-deactive";
        }
    },

    listeners: {
        create: {
            fn: function() {

                var i_self = this;
                var i_store = i_self.getStore();
                var i_model = i_store.getModel();

                var i_record = i_model.create({});

                var i_propertyStore = Ext.data.StoreManager.lookup("pd-manager-store-property");
                var i_collectionStore = Ext.data.StoreManager.lookup("pd-manager-store-collection");

                var a_properties = [];
                var a_collections = [];
                var a_forms = [];
                var i_data;
                var i_autoSource;

                i_data = i_propertyStore.getData();

                if (i_data.filtered) {
                    i_autoSource = i_data.autoSource;
                    a_properties = i_autoSource.getRange();
                }
                else {
                    a_properties = i_propertyStore.getRange();
                }

                i_data = i_collectionStore.getData();

                if (i_data.filtered) {
                    
                    i_autoSource = i_data.autoSource;
                    a_collections = i_autoSource.getRange();
                }
                else {
                    a_collections = i_collectionStore.getRange();
                }

                i_data = i_store.getData();

                if (i_data.filtered) {
                    
                    i_autoSource = i_data.autoSource;
                    a_forms = i_autoSource.getRange();
                }
                else {
                    a_forms = i_store.getRange();
                }

                var a_data = [];
                var a_extend = [];

                Ext.Array.each(a_properties, function(i_record) {
                    
                    a_data.push({
                        name: i_record.get("name")
                    });
                });

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

                    a_data.push({
                        name: i_record.get("name")
                    });
                });

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

                    a_extend.push({
                        name: i_record.get("name")
                    });
                });

                var i_propertyGrid = Ext.widget("propertygrid", {
                    title: ip2.i18n({
                        da: "Egenskaber",
                        en: "Properties"
                    }),
                    source: i_record.getData(),
                    sortableColumns: false,
                    sourceConfig: {
                        label: {
                            editor: {
                                xtype: "i18ntextfield",
                                renderer: function(value) {
                                    return ip2.i18n(value, value);
                                }
                            }
                        },
                        items: {
                            editor: {
                                xtype: "pd-manager-field-itempicker",
                                property: "name",
                                pickerTitle: ip2.i18n({
                                    da: "Vælg items",
                                    en: "Select items"
                                }),
                                rows: a_data,
                                listeners: {
                                    beforeshow: {
                                        fn: function(i_field) {
                                            
                                            var i_grid = i_field.getMultiSelector();
                                            var o_search = i_grid.getSearch();
                                            var i_searchStore = o_search.store;

                                            i_searchStore.loadRawData(a_data, false);
                                        }
                                    }
                                }
                            },
                            renderer: function(value) {
                                value = Ext.encode(value, true) || "";
                                return value;
                            }
                        },
                        extend: {
                            editor: {
                                xtype: "pd-manager-field-itempicker",
                                property: "name",
                                pickerTitle: ip2.i18n({
                                    da: "Extend",
                                    en: "Extend"
                                }),
                                rows: a_extend,
                                listeners: {
                                    beforeshow: {
                                        fn: function(i_field) {
                                            
                                            var i_grid = i_field.getMultiSelector();
                                            var o_search = i_grid.getSearch();
                                            var i_searchStore = o_search.store;

                                            i_searchStore.loadRawData(a_extend, false);
                                        }
                                    }
                                }
                            },
                            renderer: function(value) {
                                value = Ext.encode(value, true) || "";
                                return value;
                            }
                        },
                        rule: {
                            editor: {
                                xtype: "pd-manager-field-rulepicker"
                            },
                            renderer: function(value) {
                                value = Ext.encode(value, true) || "";
                                return value;
                            }
                        }
                    },
                    listeners:{
                        beforeedit: {
                            fn: function(i_editor, i_event) {
                                if (i_event.record.get("name") == "type") {
                                    return false;
                                }
                                else if (i_event.record.get("name") == "extend") {
                                    return !Ext.isEmpty(a_extend);
                                }
                                else if (i_event.record.get("name") == "items") {
                                    return !Ext.isEmpty(a_data);
                                }
                            }
                        }
                    }
                });

                var i_acetextarea = Ext.widget("acetextarea", {
                    hideLabel: true,
                    mode: "json",
                    asJson: true,
                    listeners: {
                        change: {
                            fn: function(i_field, value) {
                                if (i_field.isValid()) {
        
                                    i_propertyGrid.setSource(value);
                                }
                            },
                            buffer: 250
                        },
                        afterrender: {
                            fn: function(i_field) {
                                i_field.on({
                                    editorready: {
                                        fn: function(item) {
                                            i_field.getEditor().focus(false, 100);
                                        },
                                        buffer: 100
                                    }
                                });
                            }
                        }
                    }
                });
        
                var i_container = Ext.widget("panel", {
                    title: ip2.i18n({
                        da: "Kildetekst",
                        en: "Source code"
                    }),
                    flex: 1,
                    layout: "fit",
                    items: [
                        i_acetextarea
                    ],
                    listeners: {
                        activate: {
                            fn: function() {
        
                                var o_source = i_propertyGrid.getSource();
                                i_acetextarea.setValue(o_source);
                            }
                        }
                    }
                });

                var i_tabpanel = Ext.widget("tabpanel", {
                    items: [
                        i_propertyGrid,
                        i_container
                    ]
                });

                var i_window = Ext.widget("window", {
                    layout: "fit",
                    title: ip2.i18n({
                        da: "Ny Form Samling",
                        en: "New Form collection"
                    }),
                    height: 700,
                    width: 700,
                    modal: true,
                    items: [
                        i_tabpanel
                    ]
                });

                var i_toolbar = Ext.widget("toolbar", {
                    dock: "bottom",
                    ui: "footer",
                    items: [
                        "->",
                        {
                            xtype: "button",
                            text: ip2.i18n({
                                da: "Opret",
                                en: "Create"
                            }),
                            ui: "primary-button",
                            handler: function() {

                                var o_data = i_propertyGrid.getSource();
                                i_record.set(o_data);

                                if (!Ext.isEmpty(i_record.get("name"))) {

                                    i_store.add([
                                        i_record
                                    ]);
    
                                    i_record.commit();
    
                                    i_window.close();
                                }
                                else {
                                    ip2.messageBox({
                                        title: ip2.i18n({
                                            da: "Fejl",
                                            en: "Errror"
                                        }),
                                        message: ip2.i18n({
                                            da: "<strong>name</strong> er påkrævet",
                                            en: "<strong>name</strong> is required"
                                        }),
                                        yesText: ip2.i18n({
                                            da: "Ok",
                                            en: "Ok"
                                        })
                                    });
                                }
                            }
                        }
                    ]
                });

                i_window.addDocked(i_toolbar);

                i_window.show();
            }
        }
    },

    config: {
        values: []
    },

    initComponent: function() {

        var i_self = this;

        i_self.columns = i_self.createColumns();
        i_self.store = i_self.createStore();

        i_self.callParent(arguments);

        var i_store = i_self.getStore();
        i_store.setRemoteFilter = Ext.emptyFn;

        var i_toolbar = Ext.widget("toolbar", {
            dock: "top",
            items: [
                {
                    xtype: "searchfield",
                    store: i_self.getStore(),
                    ui: "function-field",
                    listeners: {
                        change: {
                            fn: function(i_field){

                                i_field.onSearchClick();
                            }
                        }
                    },
                    onClearClick: function() {
                        var i_field = this;
                        i_field.setValue("");
                    },
                    onSearchClick: function() {

                        var i_field = this;

                        var s_value = i_field.getValue() || "";

                        s_value = s_value.toLowerCase();

                        var i_store = i_self.getStore();
                        i_store.clearFilter(true);
                                    
                        i_store.filterBy(function(i_record) {

                            var s_id = i_record.get("name") || "";
                            var s_title = ip2.i18n(i_record.get("title"), "");

                            s_id = s_id.toLowerCase();
                            s_title = s_title.toLowerCase();

                            return s_id.indexOf(s_value) > -1 || s_title.indexOf(s_value) > -1;
                        });
                    }
                },
                {
                    xtype: "button",
                    text: ip2.i18n({
                        da: "Opret",
                        en: "Create"
                    }),
                    ui: "function",
                    handler: function() {
                        i_self.fireEvent("create", i_self);
                    }
                }
            ]
        });

        i_self.addDocked(i_toolbar);

        i_self.enableBubble([
            "propertyactivate",
            "propertydeactivate"
        ]);
    },

    createColumns: function() {

        var i_self = this;

        var a_columns = [
            {
                dataIndex: "name",
                header: "Name",
                flex:1,
                renderer: function(value, i_meta, i_record) {
                    var s_extend = i_record.get("extend");

                    if (s_extend && !Ext.isEmpty(s_extend)) {
                        value = "<span>&emsp;&emsp;-&nbsp;<span> " + value;
                    }
                    return value;
                }
            },
            {
                dataIndex: "label",
                header: "Label",
                flex:1,
                renderer: function(value) {
                    return ip2.i18n(value, value);
                }
            },
            {
                dataIndex: "extend",
                header: "Extend",
                flex:1
            },
            {
                xtype: "actioncolumn",
                align: "center",
                dataIndex: "action",
                menuDisabled: true,
                hideable: false,
                sortable: false,
                groupable: false,
                defaults: {
                    margin: "auto"
                },
                items: [
                    {
                        xtype: "button",
                        iconCls: "pf-options",
                        width: 20,
                        ui: "function-action",
                        handler: function (i_grid, n_row, n_column, i_item, i_event, i_record, i_row) {

                            var i_menu = Ext.widget("menu", {
                                plain: true,
                                items: [
                                    {
                                        xtype: "menuitem",
                                        itemId: "form-item-activate",
                                        text: ip2.i18n({
                                            da: "Aktiver",
                                            en: "Activate"
                                        }),
                                        handler: function (i_item) {

                                            i_record.set("active", true);
                                            i_record.commit(true);
        
                                            i_self.fireEvent("collectionactivate", i_record);
                                        }
                                    },
                                    {
                                        xtype: "menuitem",
                                        itemId: "form-item-deactivate",
                                        text: ip2.i18n({
                                            da: "Deaktiver",
                                            en: "Deactivate"
                                        }),
                                        handler: function (i_item) {
        
                                            i_record.set("active", false);
                                            i_record.commit(true);
        
                                            i_self.fireEvent("collectiondeactivate", i_record);
                                        }
                                    },
                                    {
                                        xtype: "menuitem",
                                        itemId: "form-item-delete",
                                        text: ip2.i18n({
                                            da: "Slet",
                                            en: "Delete"
                                        }),
                                        handler: function (i_item) {
        
                                            ip2.messageBox({
                                                title: ip2.i18n({
                                                    da: "Bekræft slet",
                                                    en: "Confirm Delete"
                                                }),
                                                message: ip2.i18n({
                                                    da: "Er du sikker på du vil slette..?",
                                                    en: "Are you sure you want to delete"
                                                }),
                                                yesText: ip2.i18n({
                                                    da: "Ja",
                                                    en: "Yes"
                                                }),
                                                noText: ip2.i18n({
                                                    da: "Nej",
                                                    en: "No"
                                                }),
                                                yesFn: function () {
        
                                                    var i_store = i_self.getStore();
        
                                                    i_store.remove(i_record);
                                                }
                                            });
                                        }
                                    }
                                ],
                                listeners: {
                                    beforeshow: {
                                        fn: function(i_menu) {
        
                                            var b_active = i_record.get("active");
        
                                            var i_activate = i_menu.getComponent("form-item-activate");
                                            var i_deactivate = i_menu.getComponent("form-item-deactivate");
        
                                            i_activate[b_active ? "disable" : "enable"]();
                                            i_deactivate[b_active ? "enable" : "disable"]();
                                        }
                                    }
                                }
                                
                            });

                            i_menu.showAt(i_event.getXY());
                        }
                    }
                ]
            }
        ];

        return a_columns;
    },

    createStore: function() {

        var i_self = this;

        var a_data = i_self.getValues();

        var i_store = Ext.create("Ext.data.Store", {
            model: "Portfolio.pd.manager.component.grid.model.Form",
            data: a_data
        });

        return i_store;
    }
});