(function(){
    var Ext = window.Ext4 || window.Ext;

    /**
     * @private
     * A small widget for displaying a user's most recently used projects.
     * Driven by a user preference with the key "workspace.{workspaceOid}.mruprojects".
     *
     *      @example
     *      Ext.create('Rally.ui.picker.MostRecentlyUsedProjects', {
     *          workspaceObjectID: Rally.environment.getContext().getWorkspace().ObjectID,
     *          renderTo: Ext.getBody().dom
     *      });
     */
    Ext.define('Rally.ui.picker.project.MostRecentlyUsedProjects', {
        extend: 'Ext.Container',
        alias: 'widget.rallymostrecentlyusedprojects',

        componentCls: 'mostRecentlyUsedProjects',

        config: {
            /**
             * @cfg {Number} (required)
             * The workspace oid to grab the most recently used projects for.
             */
            workspaceObjectID: undefined,

            getProjectsFn: undefined
        },

        constructor: function(config){
            this.initConfig(config);
            this.callParent(arguments);
        },

        initComponent: function(){
            this.callParent(arguments);

            this.addEvents(
                    /**
                     * @event
                     * Fired when a recent project is selected
                     * @param {Rally.data.wsapi.Model} project the selected project
                     */
                    'select',

                    /**
                     * @event
                     * Fired after the recent projects have loaded and drawn
                     * @param {Rally.data.wsapi.Model[]} projects the recent projects
                     */
                    'load'
            );

            this._loadMostRecentlyUsedProjects({
                success: this._drawMostRecentlyUsedProjects,
                scope: this
            });
        },

        _loadMostRecentlyUsedProjects: function(options){

            Rally.data.PreferenceManager.load({
                cache: false,
                filterByUser: true,
                filterByName: this._getPrefName(),
                success: function(pref){
                    var prefValue = pref[this._getPrefName()];
                    if(!prefValue){
                        options.success.call(options.scope, []);
                        return;
                    }
                    var oids = prefValue.split(',');

                    this._loadProjects(options, oids);
                },
                scope: this
            });
        },

        _loadProjects: function(options, oids) {
            var filter = this._buildFilter(oids);

            Ext.create('Rally.data.wsapi.Store', {
                model: Ext.identityFn('project'),
                autoLoad: true,
                fetch: ['Name'],
                filters: filter,
                listeners: {
                    load: function(store, projects) {
                        var sortedProjects = this._sortProjects(oids, projects);
                        options.success.call(options.scope, sortedProjects);
                    },
                    scope: this
                }
            });
        },

        _sortProjects: function(oids, projects){
            return Ext.Array.sort(projects, function(project1, project2){
                return Ext.Array.indexOf(oids, project1.get('ObjectID')+'') - Ext.Array.indexOf(oids, project2.get('ObjectID')+'');
            });
        },

        _getPrefName: function(){
            return 'workspace.' + this.getWorkspaceObjectID() + '.mruprojects';
        },

        _buildFilter: function(oids){
            var filter;
            Ext.each(oids, function(oid, index){
                if(index === 0){
                    filter = Ext.create('Rally.data.wsapi.Filter', {
                        property: 'ObjectID',
                        value: oid
                    });
                } else {
                    filter = filter.or({
                        property: 'ObjectID',
                        value: oid
                    });
                }
            });

            return filter;
        },

        _drawMostRecentlyUsedProjects: function(projects){

            if(projects.length === 0){
                this.fireEvent('load', projects);
                return;
            }

            var projectItems = _.map(projects, function(project){
                return {
                    xtype: 'component',
                    autoEl: 'li',
                    cls: 'most-recently-used-project-item',
                    renderTpl: '<a href="#">{Name}</a>',
                    renderData: project.data,
                    renderSelectors: {
                        link: 'a'
                    },
                    listeners: {
                        click: {
                            element: 'link',
                            fn: function(){
                                this.fireEvent('select', project);
                            },
                            stopEvent: true
                        },
                        scope: this
                    },
                    project: project
                };
            }, this);

            this.add({
                xtype: 'container',
                cls: 'mostRecentlyUsedProjectsContent',
                items: [
                    {
                        xtype: 'component',
                        autoEl: 'label',
                        html: 'Recent Projects'
                    },
                    {
                        xtype: 'container',
                        autoEl: 'ul',
                        items: projectItems
                    }
                ]
            });

            this.fireEvent('load', projects);

        }

    });

})();