/*/
/ ChatZilla - Auto-TinyURL
/ http://rdmsoft.com/
/*/

plugin.id = "tinyurl";

plugin.init =
function init(glob)
{
    plugin.major = 0;
    plugin.minor = 3;
    plugin.version = plugin.major + "." + plugin.minor;
    plugin.description = "Automatic TinyURL generator";
    plugin.prefary = plugin.prefary.concat([["maxlen", 80, ""]]);
    plugin.reqVersion = "0.9.68";
}

plugin.disable =
function disable()
{
    client.commandManager.removeCommands(plugin.cmdary);

    client.sayToCurrentTarget = plugin.sayToCurrentTarget_orig;

    display("TinyURL plugin " + plugin.version + " disabled.");
    return true;
}

plugin.enable =
function enable()
{
    if(compareVersions(__cz_version, plugin.reqVersion) == 1)
    {
        display("TinyURL plugin requires ChatZilla " + plugin.reqVersion +
                " or later.", MT_ERROR)
        return false;
    }

    plugin.cmdary = [["tinyurl", plugin.onCmd, CMD_CONSOLE, "<longurl>"]];
    client.commandManager.defineCommands(plugin.cmdary);
    client.commandManager.commands.tinyurl.help = "Makes a TinyURL.";

    plugin.sayToCurrentTarget_orig = client.sayToCurrentTarget;
    client.sayToCurrentTarget = plugin.sayToCurrentTarget;

    display("TinyURL plugin " + plugin.version + " enabled.");
    return true;
}

plugin.onCmd =
function tup_onCmd(e) 
{
    var done = false;
    function tup_onCmd_slow()
    {
        if(!done)
            display("Making TinyURL...");
    };
    function tup_onCmd_callback(success, text)
    {
        display((success ? "Created" : "Failed") + " <" + text + ">.");
        done = true;
    };
    setTimeout(tup_onCmd_slow, 500);
    plugin.makeTinyUrl(e.longurl, tup_onCmd_callback);
}

plugin.sayToCurrentTarget =
function tup_cli_say(msg)
{
    if ("say" in client.currentObject)
    {
        msg = filterOutput(msg, "PRIVMSG", client.currentObject);

        if(plugin.tinyUrlify(msg, client.currentObject))
            return;

        display(msg, "PRIVMSG", "ME!", client.currentObject);
        client.currentObject.say(msg);

        return;
    }

    switch (client.currentObject.TYPE)
    {
        case "IRCClient":
            dispatch("eval", {expression: msg});
            break;

        default:
            if (msg != "")
                display(MSG_ERR_NO_DEFAULT, MT_ERROR);
            break;
    }
}

// if message contains long URL(s), returns true and creates TinyURLs asyncly
plugin.tinyUrlify =
function tup_tinyUrlify(msg, obj)
{
    var linkRE = new RegExp(client.linkRE.source, "g");
    var urlAry, schemeAry, url, longUrls = new Array();
    while(urlAry = linkRE.exec(msg))
    {
        url = urlAry[1];
        schemeAry = url.match(/^(\w[\w-]+):/);
        if(schemeAry)
        {
            if(schemeAry[1] != "http") // todo: make this a pref
                continue;
        }
        else
            url = "http://" + url;

        if(url.length > plugin.prefs.maxlen)
            longUrls.push(url);
    }

    if(longUrls.length == 0)
        return false;

    var plururl = (longUrls.length > 1);

    function tup_tinyUrlify_slow()
    {
        if(!done)
            obj.display("Making TinyURL" + (plururl ? "s" : "") + "...");
    };
    function tup_tinyUrlify_callback(success, text)
    {
        if(success)
            msg = msg.replace(currentLongUrl, text);
        else
            obj.display("Failed to create TinyURL <" + text + ">.");

        if(currentLongUrl = longUrls.pop())
            plugin.makeTinyUrl(currentLongUrl, tup_tinyUrlify_callback);
        else
        {
            done = true;
            display(msg, "PRIVMSG", "ME!", obj);
            obj.say(msg);
        }
    };
    setTimeout(tup_tinyUrlify_slow, Math.max(500, 250*longUrls.length));

    var currentLongUrl = longUrls.pop();
    plugin.makeTinyUrl(currentLongUrl, tup_tinyUrlify_callback);
    return true;
}

// creates TinyURL asyncly and notifies callback
plugin.makeTinyUrl =
function tup_makeTinyUrl(longUrl, callback)
{
    var XHR = new XMLHttpRequest();
    XHR.onreadystatechange = function tup_onreadystatechange()
    {
        if(XHR.readyState != 4)
            return;
        try
        {
            if(XHR.status == 200)
            {
                var pat = /<b>(http:\/\/tinyurl\.com\/\w+)<\/b>/;
                var mat = XHR.responseText.match(pat);
                if(mat && mat[1])
                    callback(true, mat[1] + frag);
                else
                    callback(false, "scrape error");
            }
            else
                callback(false, XHR.status + " " + XHR.statusText);
        }
        catch(ex)
        {
            callback(false, "connection error");
        }
    };
    var hashpos = longUrl.indexOf("#"), frag;
    if(hashpos == -1)
    {
        frag = "";
//        longUrl = longUrl.replace("&", "%26");
    }
    else
    {
        frag = longUrl.substr(hashpos)
        longUrl = longUrl.substr(0, hashpos).replace("&", "%26");
    }
    XHR.open("GET", "http://tinyurl.com/create.php?url=" + longUrl, true);
    XHR.send(null);
}
