﻿(function(Varas, $) {
    var OO = Varas.OO,
    //Log = Varas.Log,
        Observable = OO.Observable,
        Twitter = Varas.ns(Varas, 'Twitter');
    /**
    * @class Varas.Twitter.Search
    * Requires: Rx.js, jQuery
    */
    Twitter.User = OO.extend(Observable, {
        url: 'http://twitter.com/statuses/user_timeline/249563832.json',
        /* maxResults: the maximum number of results to return */
        maxResults: 100,

        constructor: function(config) {
            Varas.applyTo(this, config);
            this.addEvents('load', 'tweet');

        },
        /** start the search */
        start: function(query) {
            var me = this;

            //Log.debug("Search: " + me.query);
            $.ajax({
                url: me.url,
                timeout: 5000 * 10,
                dataType: 'jsonp',
                type: 'GET',
                success: function(data, textStatus, XMLHttpRequest) {

                    me.dispatchEvent('load', {
                        raw: data,
                        results: data.results
                    });
                    //send events for the individual tweets
                    if (me.hasEventListeners('tweet')) {
                        var t = data.results;
                        for (var i = 0, l = t.length; i < l; i++) {
                            me.dispatchEvent('tweet', t[i]);
                        }
                    }

                }
            });
            return me;
        }

    });
})(Varas, window.jQuery);

$(document).ready(function() {

    //start a search on twitter
    var s = new Varas.Twitter.User({
        maxResults: 5
    }).start();

    // s.on('load', function(e) {
    //    ...
    // });

    //convert the search to an observable, listening to the "load" event
    var ob = s.toRxObservable('load')
    .Select(function(e) {
        if (!e.data || !e.data.raw) {
            return [];
        }
        //we only need the results array, remove the rest.
//        var tmp = [];
//        for (var i = 0; i < 5; i++)
//            tmp.push(e.data.raw[0]);
//        return tmp;
        return e.data.raw;
    })
    .Select(function(tweets) {
        Varas.Log.info('found ' + tweets.length + ' tweets');
        //sort the tweets, so that the oldest is first in the array
        // there is no need to parse the dates, just compare the id's
        Varas.sortArray(tweets, function(a, b) {
            return a.id - b.id;
        });
        /* Create an observable from the array with a custom scheduler
        so the tweets arrive at regular intervals of 500 ms instead of all at once */
        return Rx.Observable.FromArray(tweets, Varas.Rx.DelayedScheduler(500));
    })
    .Switch()
    .Select(function(tweet) {

        //preload the image for this tweet
        var avatar = new Image();
        avatar.src = tweet.profile_image_url;

        //normalize the tweet object and return the new object
        return {
            id: tweet.id,
            avatar: tweet.profile_image_url,
            text: tweet.text,
            date: tweet.created_at,
            geo: tweet.geo
        };
    })
    /* delay the stream a little bit so the image has a chance to be downloaded in time */
    .Delay(250);

    //subscribe to the observable
    ob.Subscribe(handleTweet);

    /** process a single tweet */
    function handleTweet(tweet) {
        var container = handleTweet.container;
        if (!handleTweet.counter) {
            handleTweet.counter = 0;
            //fetch a reference to the tweet container
            container = handleTweet.container = $('#tweets');
        }

        var t = $('<div />', { 'class': 'tweet', id: 'T' + tweet.id });
        //$('<img />', { 'class': 'avatar', src: tweet.avatar }).appendTo(t);
        $('<div />', { 'class': 'text' }).appendTo(t).html('<a href="http://twitter.com/societeithaven" target="_blank"><b>societeithaven</b></a>' + ' ' + tweet.text);
        $('<div style="color:#ABB0B3;" />', { 'class': 'date' }).appendTo(t).text(formatDate(tweet.date));

        // console.log('Data: ' + tweet);
        // console.dir(tweet);
        t.prependTo(container);

        if (handleTweet.counter++ > 4) {
            handleTweet.counter = 0;
            //keep the first 10 tweets, remove the rest
            container.children('.tweet:gt(10)').remove();
        }
    };

    function formatDate(date) {
        return date.substring(0, date.lastIndexOf(':') + 3);
    }
});
