Ext.define("Portfolio.ux.sql.template.view.Main", {
  extend: "Ext.grid.Panel",

  controller: "sql.template.controller.main",

  alias: "widget.sql.template.view.main",

  requires: [
    "Portfolio.dynapp.view.Toolbar",
    "Portfolio.ux.sql.template.controller.Main"
  ],

  config: {
    template: "",
    toolbar: null,
    sqlCmd: ""
  },

  initComponent: function() {

    var i_self = this;

    Ext.apply(i_self, {
      columns: [],
      store: i_self.createStore(),
      selModel: {
        type: "spreadsheet"
     },
     plugins: [
       {
         ptype: "clipboard"
       }
     ]
    });

    i_self.callParent(arguments);

    var i_controller = i_self.getController();

    i_controller.getMetaInfo(function(o_data) {
        i_self.updateColumns(o_data);
    });
  },

  createStore: function() {

    var i_self = this;

    var i_store = Ext.create("Ext.data.Store", {
      autoLoad: false,
      fields: [],
      proxy: {
          type: "ajax",
          url: "/ip2-services/ip2DmdProxy.aspx",
          paramsAsJson: true,
          reader: {
              type: "json",
              rootProperty: "batch[0].rows",
              totalProperty: "batch[0].totalRows"
          },
          actionMethods: {
              read: "POST"
          }
      },
      listeners: {
        beforeload: {
          fn: function(i_store, i_operation) {

            var i_proxy = i_store.getProxy();
            var o_extraParams = i_proxy.getExtraParams();

            var s_cmd = i_self.getSqlCmd();

            if (o_extraParams.hasOwnProperty("where")) {
              s_cmd = s_cmd + "where " + o_extraParams.where;
              delete o_extraParams.where;
            }

            var a_batch = [{
              cmd: s_cmd,
              limit: 1000,
              meta: true,
              start: 0,
              type: "sql"
            }];

            Ext.apply(o_extraParams, {
              batch: a_batch
            });
          }
        }
      }
    });

    return  i_store;
  },

  createToolbar: function() {

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

    var i_filterbar = Ext.widget("dynapp.toolbar", {
			dock: "top",
			grid: i_self,
			allowMenu: false,
			defaultFilter: ""
		});

    i_self.setToolbar(i_filterbar);

    i_self.addDocked(i_filterbar);
  },

  updateColumns: function(o_data) {

    var i_self = this;

    var o_meta = o_data.metaData || {};

    var a_columns = [];

    Ext.Array.each(o_meta.fields, function(o_field) {

        var o_column = {
          dataIndex: o_field.name,
          header: o_field.header,
          flex: 1,
          type: o_field.datatype
        };

        a_columns.push(o_column);
    });

    i_self.reconfigure(null, a_columns);

    var i_store = i_self.getStore();

    i_self.createToolbar();

    i_store.load();
  }
});
