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

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

    requires: [
        "Portfolio.pd.manager.component.grid.model.Property",
        "Portfolio.pd.manager.component.field.ValuePicker"
    ],

    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 a_properties = [];
                var i_data;
                var i_autoSource;

                i_data = i_store.getData();

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

                var a_data = [];

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

                var i_propertyGrid = Ext.widget("propertygrid", {
                    title: ip2.i18n({
                        da: "Egenskaber",
                        en: "Properties"
                    }),
                    source: i_record.getData(),
                    sortableColumns: false,
                    sourceConfig: {
                        extend: {
                            editor: {
                                xtype: "pd-manager-field-itempicker",
                                property: "name",
                                pickerTitle: ip2.i18n({
                                    da: "Extend",
                                    en: "Extend"
                                }),
                                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;
                            }
                        },
                        rule: {
                            editor: {
                                xtype: "pd-manager-field-rulepicker"
                            },
                            renderer: function(value) {
                                value = Ext.encode(value, true) || "{}";
                                return value;
                            }
                        },
                        label: {
                            editor: {
                                xtype: "i18ntextfield",
                                renderer: function(value) {
                                    return ip2.i18n(value, value);
                                }
                            }
                        },
                        values: {
                            editor: {
                                xtype: "pd-manager-field-valuepicker",
                            },
                            renderer: function(value) {

                                var a_values = Ext.Array.from(value);
                                var a_result = []; 
                                
                                Ext.Array.each(a_values, function(o_value) {

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

                                    a_result.push(o_out);
                                });

                                value = Ext.encode(a_result, true) || "";
                                return value;
                            }
                        },
                        uom: {
                            editor: {
                                xtype: "pd-manager-field-valuepicker"
                            },
                            renderer: function(value) {

                                var a_values = Ext.Array.from(value);
                                var a_result = []; 
                                
                                Ext.Array.each(a_values, function(o_value) {

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

                                    a_result.push(o_out);
                                });

                                value = Ext.encode(a_result, 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_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 Egenskab",
                        en: "New property"
                    }),
                    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();
            }
        },
        edit: {
            fn: function(s_property, s_type) {

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

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

                i_data = i_store.getData();

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

                var i_record = Ext.Array.findBy(a_properties, function(i_record) {
                    return i_record.get("name") == s_property;
                });

                if (i_record) {

                    var a_data = [];

                    Ext.Array.each(a_properties, function(i_record) {
                        a_data.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: {
                            extend: {
                                editor: {
                                    xtype: "pd-manager-field-itempicker",
                                    property: "name",
                                    pickerTitle: ip2.i18n({
                                        da: "Extend",
                                        en: "Extend"
                                    }),
                                    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;
                                }
                            },
                            rule: {
                                editor: {
                                    xtype: "pd-manager-field-rulepicker"
                                },
                                renderer: function(value) {
                                    value = Ext.encode(value, true) || "";
                                    return value;
                                }
                            },
                            values: {
                                editor: {
                                    xtype: "pd-manager-field-valuepicker",
                                },
                                renderer: function(value) {

                                    var a_values = Ext.Array.from(value);
                                    var a_result = []; 
                                    
                                    Ext.Array.each(a_values, function(o_value) {

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

                                        a_result.push(o_out);
                                    });

                                    value = Ext.encode(a_result, true) || "";
                                    return value;
                                }
                            },
                            uom: {
                                editor: {
                                    xtype: "pd-manager-field-valuepicker"
                                },
                                renderer: function(value) {

                                    var a_values = Ext.Array.from(value);
                                    var a_result = []; 
                                    
                                    Ext.Array.each(a_values, function(o_value) {

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

                                        a_result.push(o_out);
                                    });

                                    value = Ext.encode(a_result, 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") == "name") {
                                        return false;
                                    }
                                    else if (i_event.record.get("name") == "extend") {
                                        return !Ext.isEmpty(a_data);
                                    }
                                }
                            }
                        }
                    });

                    var i_acetextarea = Ext.widget("acetextarea", {
                        hideLabel: true,
                        mode: "json",
                        asJson: true,
                        value: i_record.getData(),
                        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", {
                        tabBar: {
                            items: [
                                {
                                    xtype: "tbfill"
                                },
                                {
                                    xtype: "button",
                                    iconCls: "pf-options",
                                    width: 20,
                                    ui: "function-action",
                                    arrowVisible: false,
                                    menu: {
                                        plain: true,
                                        items: [
                                            {
                                                xtype: "menuitem",
                                                itemId: "property-item-activate",
                                                text: ip2.i18n({
                                                    da: "Aktiver",
                                                    en: "Activate"
                                                }),
                                                handler: function (i_item) {

                                                    var o_values = i_propertyGrid.getSource();

                                                    i_record.set(o_values);

                                                    i_record.set("active", true);
                                                    i_record.commit(true);

                                                    i_propertyGrid.setSource(i_record.getData());
                
                                                    i_self.fireEvent("propertyactivate", i_record);
                                                }
                                            },
                                            {
                                                xtype: "menuitem",
                                                itemId: "property-item-deactivate",
                                                text: ip2.i18n({
                                                    da: "Deaktiver",
                                                    en: "Deactivate"
                                                }),
                                                handler: function (i_item) {
                
                                                    var o_values = i_propertyGrid.getSource();

                                                    i_record.set(o_values);

                                                    i_record.set("active", false);
                                                    i_record.commit(true);

                                                    i_propertyGrid.setSource(i_record.getData());
                
                                                    i_self.fireEvent("propertydeactivate", i_record);
                                                }
                                            },
                                            {
                                                xtype: "menuitem",
                                                itemId: "property-item-usages",
                                                text: ip2.i18n({
                                                    da: "Anvendelse",
                                                    en: "Usages"
                                                }),
                                                handler: function (i_item) {
        
                                                    var s_name = i_record.get("name");
        
                                                    i_self.fireEvent("checkproperty", s_name);   
                                                }
                                            }
                                        ],
                                        listeners: {
                                            beforeshow: {
                                                fn: function(i_menu) {
                
                                                    var b_active = i_record.get("active");
                
                                                    var i_activate = i_menu.getComponent("property-item-activate");
                                                    var i_deactivate = i_menu.getComponent("property-item-deactivate");
                
                                                    i_activate[b_active ? "disable" : "enable"]();
                                                    i_deactivate[b_active ? "enable" : "disable"]();
                                                }
                                            }
                                        }
                                    }
                                },
                                {
                                    xtype: "tbspacer",
                                    width: 10
                                }
                            ]
                        },
                        items: [
                            i_propertyGrid,
                            i_container
                        ]
                    });

                    var i_window = Ext.widget("window", {
                        layout: "fit",
                        title: [
                            ip2.i18n({
                                da: "Rediger",
                                en: "Edit"
                            }),
                            s_property
                        ].join(" - "),
                        modal: true,
                        height: 700,
                        width: 700,
                        items: [
                            i_tabpanel
                        ]
                    });

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

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

                                    if (!Ext.isEmpty(i_record.get("name"))) {
        
                                        i_record.commit();
        
                                        i_window.close();

                                        i_self.fireEvent("editcomplete", s_property, s_type);
                                    }
                                    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: []
    },

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

    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_name = i_record.get("name") || "";
                            var s_label = ip2.i18n(i_record.get("label"), "");

                            s_name = s_name.toLowerCase();
                            s_label = s_label.toLowerCase();

                            return s_name.indexOf(s_value) > -1 || s_label.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([
            "editcomplete",
            "checkproperty"
        ]);
    },

    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: "property-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("propertyactivate", i_record);
                                        }
                                    },
                                    {
                                        xtype: "menuitem",
                                        itemId: "property-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("propertydeactivate", i_record);
                                        }
                                    },
                                    {
                                        xtype: "menuitem",
                                        itemId: "property-item-usages",
                                        text: ip2.i18n({
                                            da: "Anvendelse",
                                            en: "Usages"
                                        }),
                                        handler: function (i_item) {

                                            var s_name = i_record.get("name");

                                            i_self.fireEvent("checkproperty", s_name);   
                                        }
                                    },
                                    {
                                        xtype: "menuitem",
                                        itemId: "property-item-delete",
                                        text: ip2.i18n({
                                            da: "Slet",
                                            en: "Delete"
                                        }),
                                        disabled: true,
                                        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("property-item-activate");
                                            var i_deactivate = i_menu.getComponent("property-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.Property",
            storeId: "pd-manager-store-property",
            data: a_data
        });

        return i_store;
    }
});