/**
 * RExt.DataView
 * A generic DataView Panel
 * @author Chris Scott
 */
RExt.DataView = Ext.extend(Ext.Panel, {
    frame: false,
    border: false,

    layout: 'fit',

    autoHeight: true,
    //afterPageText: 'Bq.content.DataView.afterPageText {1}',

    /**
     * @cfg {Ext.data.Record} recordType
     * store's record def'n
     */
    recordType : null,

    /**
     * @cfg {Ext.data.Record} record
     * record instance
     */
    record : null,

    /**
     * @cfg {Number} pageSize
     */
    pageSize: 10,

    /**
     * @cfg {String} templateId [content_template]
     * id of XTemplate to load from RExt.TemplateMgr
     */
    templateId : 'content_template',

    // private
    _defaultViewConfig : {
        multiSelect: true,
        deleted: [],
        deferEmptyText: true,
        overClass:'x-grid3-row-over',
        itemSelector:'div.x-grid3-row',
        selectedClass: 'x-grid3-row-selected',
        emptyText: '<h2>No items added</h2><h3 class="icon-information r-icon-text">You may add any number of items.</h3>'
    },

    /**
     * @cfg {Object} baseParams [{}]
     * baseParams appended to all DataView requests
     */
    baseParams : {},

    /**
     * @cfg {Object} viewConfig [{}]
     * extra config params sent to Ext.DataView
     */
    viewConfig : {},

    /**
     * @cfg {String} controller
     * The data-url to the mother-ship
     */
    controller : '/',

    /**
     * @cfg {Object} actions
     * actions to call on server
     */
    actions: {
        search : 'search'
    },

    initComponent : function() {
        this.addEvents({
            /**
             * @event toolclick
             * fires when an Element having class "tool" is clicked.  often an <a class="tool"></a>
             * @param {DataView} view
             * @param {Number} index
             * @param {Element} clicked-node
             * @param {EventObject} ev
             */
            toolclick : true,

            /**
             * @event select
             * same as Ext.DataView
             */
            select : true
        });

        this.addClass('r-dataview');
        // build the DataView
        this.items = this.build();

        // super
        RExt.DataView.superclass.initComponent.call(this);
    },

    /**
     * getView
     * @return {Ext.DataView}
     */
    getView : function() {
        return this.items.first();
    },

    // private
    load : function(page) {
        var bbar = this.getBottomToolbar();
        if (bbar != null) {
            bbar.changePage(page);
        }
        else {
            this.getView().store.load();
        }
        this.doLayout();    // <-- this is necessary for some stupid reason.
    },

    // private
    build : function() {
        var store = this.buildStore();
        this.tbar = this.buildTopToolbar(store);
        this.bbar = this.buildBottomToolbar(store);
        // create and return view
        var dvconfig = Ext.apply({
            id: this.id + '_view',
            store: store,
            tpl: this.getTemplate(),
            listeners : {
                click: this.onClick,
                scope: this
            }
        }, this.viewConfig, this._defaultViewConfig);
        return new Ext.DataView(dvconfig);
    },

    buildStore : function(params) {
        params = params || {};

        var url = this.controller + '/' + this.actions.search;
        if (this.record != null) { url += '/' + this.record.data.id }

        var cfg = Ext.apply({
            autoLoad: {
                params : {
                    limit: this.pageSize,
                    start: 0
                }
            },
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'data',
                id: 'id'
            }, this.recordType),
            proxy: new Ext.data.HttpProxy({
                url: url,
                method: "GET"
            }),
            baseParams : this.baseParams

        },params);
        if (this.autoLoad === false) {
            cfg.autoLoad = false;
        }

        return new Ext.data.Store(cfg);
    },

    // private @return {Ext.XTemplate}
    getTemplate : function() {
        return (this.templateId != null) ? RExt.util.TemplateMgr.get(this.templateId) : new Ext.XTemplate(
            '<tpl for=".">',
                '<div id="content-{id}" class="content-row x-grid3-row x-unselectable">{title}</div>',
            '</tpl>'
        );
    },

    buildTopToolbar : function(store) {
        return new Ext.PagingToolbar({
            store: store,
            pageSize: this.pageSize,
            displayInfo: false
        });
    },

    buildBottomToolbar : function(store) {
        return new Ext.PagingToolbar({
            store: store,
            pageSize: this.pageSize,
            displayInfo: false
        });
    },

    /**
     * onClick
     * @param {Object} v
     * @param {Object} index
     * @param {Object} node
     * @param {Object} ev
     */
    onClick : function(v, index, node, ev) {

        // look for clicked <a>
        var btn = ev.getTarget('a', 4, true);
        if (btn == null) {
            this.fireEvent('select', v, index, node, ev);    // <-- simply fire select event
            return false;   // <-- no tool clicked.  GTFO
        }

        // did user click a tool?  give chance for any Plugins to service this toolclick event
        if (btn.hasClass('tool')) {
            return this.fireEvent('toolclick', v, index, node, btn, ev);
        }
        // link with an href?  redir regular <a href="/url">
        else if (btn.dom.href) {
            document.location = btn.dom.href;
        }
    },

    onLoad : function (store, records, options) {
        console.log('onLoad fired store=%o, records=%o, options=%o', store, records, options);
    }
});