Ext.define("Portfolio.entity.plugin.Summary", {

    extend: "Ext.plugin.Abstract",

	alias: [
        "plugin.entity-grid-summary"
    ],

	config: {
        grid: null,
    },
    
    constructor: function(o_config) {

        var i_self = this;
        i_self.initConfig(o_config);
    },

	init: function(i_grid) {

		var i_self = this;
        i_self.setGrid(i_grid);
        i_self.addButton();
	},

	addButton: function() {

        var i_self = this;
        var i_grid = i_self.getGrid();
        var i_view = i_grid.getView();
        var i_store = i_grid.getStore();
        var i_model = i_store.getModel();

        var i_feature = i_view.featuresMC.getRange().find(function(i_record){
            return i_record.ftype == "grouping";
        });

        if (i_feature) {

            i_self.createTemplate(i_feature);

            i_grid.on({
                afterrender: {
                    fn: function() {

                        var i_menu = i_grid.headerCt.getMenu();

                        var i_groupingToogleItem = i_menu.getComponent("groupToggleMenuItem");

                        i_groupingToogleItem.on({
                            checkchange: {
                                fn: function(i_item, b_checked) {

                                    var i_summary = i_menu.getComponent("button-summary");

                                    if (i_summary) {
                                        i_summary[b_checked ? "show" : "hide"]();
                                    }
                                }
                            }
                        });

                        i_menu.on({
                            beforeshow: {
                                fn: function(i_menu) {

                                    i_feature = i_view.featuresMC.getRange().find(function(i_record){
                                        return i_record.ftype == "grouping";
                                    });

                                    var i_summary = i_menu.getComponent("button-summary");
                                    var i_activeColumn = i_menu.activeHeader;

                                    var i_field = i_model.getField(i_activeColumn.dataIndex);

                                    var a_items = [];

                                    if (i_summary) {
                                        i_menu.remove(i_summary);
                                    }

                                    if (i_field.type == "number" || i_field.type == "int") {
                                        a_items = [{
                                            xtype: "menucheckitem",
                                            itemId: "sum",
                                            text: ip2.i18n({
                                                da: "Sum",
                                                en: "Sum"
                                            }),
                                            checked: i_activeColumn.sum,
                                            checkHandler: function(i_item, b_checked) {
                                                 var i_column = i_menu.activeHeader;
                                                i_column.sum = b_checked;
                                                i_view.refresh();
                                            }
                                        },
                                        {
                                            xtype: "menucheckitem",
                                            itemId: "min",
                                            text: ip2.i18n({
                                                da: "Minimum",
                                                en: "Minimum"
                                            }) + "<span style=\"margin-left: 2px;\" class=\"pf-sort_down\"></span>",
                                            checked: i_activeColumn.min,
                                            checkHandler: function(i_item, b_checked) {
                                                 var i_column = i_menu.activeHeader;
                                                i_column.min = b_checked;
                                                i_view.refresh();
                                            }
                                        },
                                        {
                                            xtype: "menucheckitem",
                                            itemId: "max",
                                            text: ip2.i18n({
                                                da: "Maximum",
                                                en: "Maximum"
                                            }) + "<span style=\"margin-left: 2px;\" class=\"pf-sort_up\"></span>",
                                            checked: i_activeColumn.max,
                                            checkHandler: function(i_item, b_checked) {
                                                 var i_column = i_menu.activeHeader;
                                                i_column.max = b_checked;
                                                i_view.refresh();
                                            }
                                        },
                                        {
                                            xtype: "menucheckitem",
                                            itemId: "avg",
                                            text: ip2.i18n({
                                                da: "Gennemsnit",
                                                en: "Average"
                                            }) + "<span style=\"margin-left: 2px;\" class=\"pf-sort_up_down\"></span>",
                                            checked: i_activeColumn.avg,
                                            checkHandler: function(i_item, b_checked) {
                                                 var i_column = i_menu.activeHeader;
                                                i_column.avg = b_checked;
                                                i_view.refresh();
                                            }
                                        }].concat(a_items);

                                        i_summary = Ext.widget("menuitem", {
                                            itemId: "button-summary",
                                            text: ip2.i18n({
                                                da: "Summering",
                                                en: "Summary"
                                            }),
                                            iconCls: "pf-sum",
                                            menu: {
                                                items: a_items
                                            }
                                        });
    
                                        var n_index = i_menu.items.indexOf(i_groupingToogleItem);
    
                                        i_menu.add(n_index + 1, i_summary);
                                    }
                                    
                                }
                            }
                        });
                    }
                }
            });            
        }
    },
    
    createTemplate: function(i_feature) {

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

        var i_calctemplate = Ext.create("Ext.XTemplate",
            "<tpl>",
                "<span style=\"margin-left: 5px;\">{value}<span>",
                "<tpl if=\"class\">",
                    "<span style=\"font-size:12px;\"class={class}></span>",
                "</tpl>",
            "</tpl>"
        );

        var i_renderTpl  = Ext.create("Ext.XTemplate",
            "<strong><span>{name}</span></strong>",
            "<span style=\"margin-left: 20px; font-weight:400;\">{extra}<span>",
            "<strong><span style=\"",
                "float:right;",
                "padding-left:10px;",
                "width: 90px;",
                "text-align: center;",
                "\">{count}</span></strong>"
        );

        var i_template = Ext.create("Ext.XTemplate",
            "{[this.getText(values, parent)]}",
            {
                getText: function(o_values, i_parent) {

                    
                    var a_rows = Ext.Array.from(o_values.rows);
                    var i_store = i_grid.getStore();
                    var i_model = i_store.getModel();

                    var i_columnManager = i_grid.getColumnManager();

                    var a_colunns = i_columnManager.getColumns();

                    var a_result = [];

                    Ext.Array.each(a_colunns, function(i_column) {

                        var a_temp = [];
                        var s_dataIndex = i_column.dataIndex;

                        var i_field = i_model.getField(s_dataIndex);

                        var s_format = "000,0";

                        var n_value = i_field ? i_field.dec : 0;

                        if (n_value > 0) {
                            s_format += "." + Ext.util.Format.repeat(n_value, "0", "");
                        }
                        
                        if (i_column.sum) {

                            var n_sum = 0;

                            Ext.Array.each(a_rows, function(i_record) {
                                n_sum += i_record.get(s_dataIndex);
                            });

                            a_temp.push(i_calctemplate.apply({
                                class: "",
                                value: Ext.util.Format.number(n_sum, s_format)
                            }));
                        }

                        if (i_column.min) {

                            var n_min = 9999999999;

                            Ext.Array.each(a_rows, function(i_record) {
                                n_min = Math.min(n_min, i_record.get(s_dataIndex));
                            });

                            a_temp.push(i_calctemplate.apply({
                                class: "pf-sort_down",
                                value: Ext.util.Format.number(n_min, s_format)
                            }));
                        }

                        if (i_column.max) {

                            var n_max = -1;

                            Ext.Array.each(a_rows, function(i_record) {
                                n_max = Math.max(n_max, i_record.get(s_dataIndex));
                            });

                            a_temp.push(i_calctemplate.apply({
                                class: "pf-sort_up",
                                value: Ext.util.Format.number(n_max, s_format)
                            }));
                        }

                        if (i_column.avg) {

                            var n_total = 0;

                            Ext.Array.each(a_rows, function(i_record) {
                                n_total += i_record.get(s_dataIndex);
                            });

                            a_temp.push(i_calctemplate.apply({
                                class: "pf-sort_up_down",
                                value: Ext.util.Format.number(Math.round(n_total / a_rows.length), s_format)
                            }));
                        }

                        a_temp = Ext.Array.filter(a_temp, function(value) {
                            return value;
                        });

                        if (a_temp.length > 0) {
                            a_result.push(
                                i_column.text + " " + a_temp.join(" ") + " "
                            );
                        }
                    });

                    return i_renderTpl.apply({
                        name: o_values.name,
                        extra: a_result.join("&nbsp;/&nbsp;&nbsp;"),
                        count: a_rows.length
                    });
                }
            }
        );

        i_feature.groupHeaderTpl = i_template;
    }
});
