Ext.define("Portfolio.pd.manager.component.panel.view.Property", {

    extend: "Ext.panel.Panel",

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

    layout: {
        type: "hbox",
        align: "stretch"
    },

    requires: [
        "Portfolio.pd.manager.component.grid.view.Property"
    ],

    config: {
        grid: null,
        propertyGrid: null,
        values: [],
        previewContainer: null,
        sourceEditor: null
    },

    listeners: {
        updatepreview: {
            fn: function(i_self, i_selected) {

                var i_preivewContainer = i_self.getPreviewContainer();

                i_preivewContainer.setLoading(true);

                setTimeout(function() {
                    Ext.suspendLayouts();

                    i_preivewContainer.removeAll(true);

                    var i_grid = i_self.getGrid();
                    var i_store = i_grid.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 a_definition = [];

                    Ext.Array.each(a_properties, function(i_record) {
                        a_definition.push(i_record.getData());
                    });

                    var o_property = i_selected.getData();

                    var o_result = Portfolio.pd.util.Handler.createProperty(o_property, a_definition, "");

                    var o_processed = {};
                    o_processed[i_selected.get("name")] = o_result;

                    var a_items = Portfolio.pd.util.Handler.createItems(o_processed);

                    i_preivewContainer.add(a_items);

                    Ext.resumeLayouts(true);

                    i_preivewContainer.setLoading(false);
                    
                }, 100);
            },
            buffer: 100
        },
        editproperty: {
            fn: function(s_property, s_type) {

                var i_self = this;
                var i_grid = i_self.getGrid();
                
                i_grid.fireEvent("edit", s_property, s_type);
            }
        }
    },

    initComponent: function() {

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

        i_self.add([
            i_self.createGrid(),
            {
                xtype: "container",
                layout: {
                    type: "vbox",
                    align: "stretch"
                },
                flex: 2,
                split: true,
                items: [
                    i_self.createPreview(),
                    i_self.createTabArea()
                ]
            }
        ]);

        i_self.enableBubble([
            "editcomplete",
            "checkproperty"
        ]);
        
    },

    createGrid: function() {

        var i_self = this;
        var a_values = i_self.getValues();

        var i_grid = Ext.widget("pd-manager-grid-property", {
            flex: 1,
            values: a_values,
            split: true,
            listeners: {
                select: {
                    fn: function(i_grid, i_selected) {
    
                        var a_data = [];
    
                        var i_store = i_grid.getStore();
    
                        var s_selected = i_selected.get("name");

                        var i_sourceEditor = i_self.getSourceEditor();

                        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();
                        }

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

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

                            a_data.push({
                                name: s_name
                            });
                        });

                        var a_filtered = Ext.Array.filter(a_data, function(o_data) {
                            return o_data.name != s_selected;
                        });
    
                        var o_sourceConfig = {
                            label: {
                                editor: {
                                    xtype: "i18ntextfield",
                                },
                                renderer: function(value) {
                                    value = ip2.i18n(value, value);
                                    return value;
                                }
                            },
                            extend: {
                                editor: {
                                    xtype: "pd-manager-field-itempicker",
                                    property: "name",
                                    pickerTitle: ip2.i18n({
                                        da: "Extend",
                                        en: "Extend"
                                    }),
                                    rows: a_filtered,
                                    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);
                                            }
                                        }
                                    }
                                }
                            },
                            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;
                                }
                            }
                        };

                        var o_data = Ext.clone(i_selected.getData());

                        delete o_data.active;
    
                        var i_propertyGrid = i_self.getPropertyGrid();
    
                        i_propertyGrid.setSource(o_data, o_sourceConfig);

                        var o_source = i_propertyGrid.getSource();
                        i_sourceEditor.suspendCheckChange++;
                        i_sourceEditor.setValue(o_source);
                        i_sourceEditor.resetOriginalValue();
                        i_sourceEditor.suspendCheckChange--;

                        i_self.fireEvent("updatepreview", i_self, i_selected);
                    }
                },
                propertyactivate: {
                    fn: function(i_record) {
                        i_self.fireEvent("updatepreview", i_self, i_record);
                    }
                },
                propertydeactivate: {
                    fn: function(i_record) {
                        i_self.fireEvent("updatepreview", i_self, i_record);
                    }
                }
            }
        });

        i_self.setGrid(i_grid);

        return i_grid;
    },

    createPropertyGrid: function() {

        var i_self = this;

        var i_propertyGrid = Ext.widget("propertygrid", {
            title:  ip2.i18n({
                da: "Værdier",
                en: "Values"
            }),
            split: true,
            flex: 1,
            source: {},
            sortableColumns: false,
            listeners:{
                beforeedit: {
                    fn: function(i_editor, i_event) {

                        if (i_event.record.get("name") == "type") {
                            return false;
                        }
                        if (i_event.record.get("name") == "name") {
                            return false;
                        }
                        else if (i_event.record.get("name") == "extend") {

                            var i_grid = i_self.getGrid();

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

                            return !Ext.isEmpty(a_data);
                        }
                    }
                },
                propertychange: {
                    fn: function(o_soruce, s_id, newValue, oldValue) {

                        var i_grid = i_self.getGrid();

                        var i_record = i_grid.getSelection()[0];
    
                        if(i_record) {

                            if(!ip2.isEqual(newValue, oldValue)) {
                                i_record.set(s_id, newValue);
                                i_record.commit();

                                i_self.fireEvent("updatepreview", i_self, i_record);
                            }
                        }
                    }
                }
            }
        });

        i_self.setPropertyGrid(i_propertyGrid);

        return i_propertyGrid;
    },

    createPreview: function() {
        
        var i_self = this;

        var i_container = Ext.widget("panel", {
            title: "Preview",
            flex: 1,
            split: true,
            bodyPadding: 10,
            layout: "anchor",
            autoScroll: true,
            defaults: {
                anchor: "90%"
            }
        });

        i_self.setPreviewContainer(i_container);

        return i_container;
    },

    createSourcePanel: function() {

        var i_self = this;

        var i_propertyGrid = i_self.getPropertyGrid();

        var i_acetextarea = Ext.widget("acetextarea", {
			hideLabel: true,
			mode: "json",
            asJson: true,
            listeners: {
                change: {
                    fn: function(i_field, value) {
                        if (i_field.isValid()) {

                            var i_grid = i_self.getGrid();
                            var i_selected = i_grid.getSelection()[0];

                            i_propertyGrid.setSource(value);

                            if (i_selected) {
                                i_selected.set(value);
                                i_selected.commit();

                                if (i_field.isVisible()) {
                                    i_self.fireEvent("updatepreview", i_self, i_selected);
                                }
                            }
                        }
                    },
                    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);
                    }
                }
            }
        });

        i_self.setSourceEditor(i_acetextarea);

        return i_container;
    },

    createTabArea: function() {

        var i_self = this;

        var i_tabpanel = Ext.widget("tabpanel", {
            flex: 1,
            split: true,
            items: [
                i_self.createPropertyGrid(),
                i_self.createSourcePanel()
            ]
        });

        return i_tabpanel;
    },

    loadData: function(a_data) {

        var i_self = this;
        var i_grid = i_self.getGrid();
        var i_store = i_grid.getStore();
        i_store.loadRawData(a_data, false);
    },

    save: function() {

        var i_self = this;
        var i_grid = i_self.getGrid();
        var i_store = i_grid.getStore();
        var a_records = [];
        var a_result = [];

        var i_data;
        var i_autoSource;

        i_data = i_store.getData();

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

        Ext.Array.each(a_records, function(i_record) {
            a_result.push(i_record.getData());
        });

        return a_result;
        
    }
});