
var express = require('express');
connect = require('connect'),
    sys = require('sys'),
    http = require('http');

function request(host, path, fn){
    sys.puts("path=" + path);

    var client = http.createClient(80, host),
    req = client.request('GET', path, {
        Host: host
    });
    req.addListener('response', function(res){
        res.body = '';
        res.addListener('data', function(chunk){
            res.body += chunk;
        });
        res.addListener('end', function(){
            try {
                fn(res.body);
            } catch (err) {
                fn(err);
            }
        });
    });
    req.end();
}

var app = express.createServer();

app.get('/user_timeline', function(req, res){
    var callback = req.param('callback'),
    name = req.param('name'),
    count = req.param('count') || 20,
    page = req.param('page') || 1;

    request("twitter.com", "/statuses/user_timeline/" + name + ".json?count=" + count + "&page=" + page,
        function(s) {
            if (callback) {
                res.contentType('respone.js');
                res.send(callback + "(" + s + ")");
            } else {
                res.contentType('respone.json');
                res.send(s);
            }
        });
});

app.get('/search', function(req, res){
    var callback = req.param('callback'),
    query = req.param('q'),
    count = req.param('count') || 20,
    page = req.param('page') || 1;

    request("search.twitter.com", "/search.json?q=/" + query + "&count=" + count + "&page=" + page,
        function(s) {
            if (callback) {
                res.contentType('respone.js');
                res.send(callback + "(" + s + ")");
            } else {
                res.contentType('respone.json');
                res.send(s);
            }
        });
});

app.listen(3000);
