﻿Ext.ns('TwitterApp');

Ext.onReady(function() {
    var usernameField = new Ext.form.TextField({
        fieldLabel: 'Username',
        allowBlank: false
    });

    var getUserPopup = new Ext.Window({
        title: 'Enter your Twitter username:',
        modal: true,
        plain: true,
        items: [new Ext.form.FormPanel({
            labelWidth: 100,
            frame: true,
            width: 300,
            height: 100,
            items: [
                usernameField
            ],
            buttons: [{
                text: 'Login',
                formBind: true,
                handler: function() {
                    var userRecord = Ext.data.Record.create([
                        { name: 'Id' }
                    ]);
                    
                    TwitterApp.Scheduler.categoryStore.add(new userRecord({
                        Id: usernameField.getValue()
                    }));

                    getUserPopup.close();
                    TwitterApp.Scheduler.init();
                }
            }]
        })]
    });
    getUserPopup.show();
    usernameField.focus(true, 500);
});


TwitterApp.Scheduler = {
    /**
     * @property
     * @type Date
     */
    start: null,

    /**
     * @property
     * @type Date
     */
    end: null,

    /**
     * @property
     * @type Ext.LoadMask
     */
    loadMask: null,

    
    /**
     * @property
     * @type Ext.data.XmlStore
     */
    eventStore: null,

    /**
     * @property
     * @type Ext.data.JsonStore
     */
    categoryStore: new Ext.data.JsonStore({
        fields: [ 
            { name: 'Id' }
        ]
    }),
    
    /**
     * @property
     * @type Sch.SchedulerPanel
     */
    app: null,
    
    /**
     * @method
     */
    setTime: function() {
        this.start = new Date();
        this.end = this.start.add(Date.DAY, 1);
        
        this.start.clearTime();
        this.end.clearTime();
    },

    /**
     * @method
     */
    loadEventData: function() {
        this.eventStore = new Ext.data.JsonStore({
            proxy: new Ext.data.ScriptTagProxy({
                url: 'http://twitter.com/statuses/user_timeline.json'
            }),
            autoLoad: true,
            baseParams: {
                screen_name: this.categoryStore.getAt(0).get('Id'),
                
                //start and end are actually irrelevant to the Twitter API...
                start: this.start,
                end: this.end, 
                
                //...so load our last 50 tweets instead
                count: 50 
            },
            fields: [
                { name: 'Id', mapping: 'id' },
                { name: 'ResourceId', mapping: 'user.screen_name' },
                { name: 'StartDate', mapping: 'created_at', type: 'date' },
                { name: 'EndDate', mapping: 'created_at', type: 'date' },
                { name: 'Title', mapping: 'text' }
            ]
        });
        this.eventStore.on(
            'load',
            function(thisStore, recordArray, options) {
                //Tweets don't have start/end times - just the time they're posted.
                //We get an error if we don't assign a valid EndDate to each record.
                
                for (var i=0; i<recordArray.length; i++) {
                    var tweet = recordArray[i];
                    var tweetTime = new Date(tweet.get('StartDate'));
                    
                    tweet.set('EndDate', tweetTime.add(Date.MINUTE, 15));
                }
            }
        );
    },

    /**
     * @method
     */
    createGrid: function() {
        var thisObject = this;
        
        var toolbarDate = new Ext.Toolbar.TextItem({
            text: this.start.format('F j, Y')
        });
        
        this.app = new Sch.SchedulerPanel({
            width: 1000,
            height: 500,
            autoScroll: true,
            autoViews: [{
                timeSpan: 1,
                columnType: 'hour',
                viewBehaviour: Sch.ViewBehaviour.HourView,
                renderer: this.renderer
            }],
            border: true,
            columns: [ 
                { header: 'Twitter Username', dataIndex: 'Id' } 
            ],
            columnLines: true,
            renderTo: Ext.getBody(),
            stripeRows: true,
            store: this.categoryStore,
            eventStore: this.eventStore,
            eventTemplate : new Ext.Template(
                '<div id="{id}" style="width:{width}px;left:{leftOffset}px" class="sch-event {cls}">' +
                    '<div class="sch-event-inner">' + 
                       '<span class="sch-event-header">{headerText}</span>' + 
                       '<div class="sch-event-footer">{footerText}</div>' + 
                   '</div>' + 
                   Sch.plugins.Resize.prototype.handleHtml +
                '</div>').compile(),
            viewConfig: { 
                forceFit: true,
                emptyText: 'No status updates found' 
            },
            tbar: [toolbarDate, '->', {
                text: 'Previous Day',
                scale: 'medium',
                iconCls: 'icon-prev',
                iconAlign: 'top',
                handler: function() {
                    var start = thisObject.app.getStart();
                    var end = thisObject.app.getEnd();

                    this.start = start.add(Date.DAY, -1);
                    this.end = end.add(Date.DAY, -1);
                    
                    toolbarDate.setText(this.start.format('F j, Y'));

                    thisObject.app.eventStore.load({
                        params : {
                            start: this.start,
                            end: this.end
                        }
                    });
                }
            }, {
                text: 'Next Day',
                scale: 'medium',
                iconCls: 'icon-next',
                iconAlign: 'top',
                handler: function() {
                    var start = thisObject.app.getStart();
                    var end = thisObject.app.getEnd();

                    this.start = start.add(Date.DAY, 1);
                    this.end = end.add(Date.DAY, 1);
                    
                    toolbarDate.setText(this.start.format('F j, Y'));

                    thisObject.app.eventStore.load({
                        params : {
                            start: this.start,
                            end: this.end
                        }
                    });
                }
            }],
            tooltipTpl : new Ext.XTemplate(
                '<dl class="eventTip">', 
                    '<dt class="icon-clock">Time</dt>',
                        '<dd>{[values.StartDate.format("G:i")]}</dd>',
                    '<dt class="icon-task">Message</dt>',
                        '<dd>{Title}</dd>',
                '</dl>').compile()
        });
        
        this.loadMask = new Ext.LoadMask(
            this.app.getEl(),
            {
                msg: 'Loading data from the Twitter API...',
                store: this.eventStore
            }
        );
    },

    /**
     * @method
     */
    renderer: function(item, m, r, row, col, ds) {
        return {
            headerText: new Date(item.get('StartDate')).format('G:i'),
            footerText: item.get('Title'),
            cls: 'Test'
        };
    },

    /**
     * @method
     */
    init: function() {
        this.setTime();
        this.loadEventData();
        this.createGrid();
    }
};