/*-*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
    mycolor plugin for Chatzilla.  Prepends mIRC control codes to your text.
    Copyright (C) 2004  John J Foerch

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

plugin.id = 'mycolor';
const __maj_version = 0
const __min_version = 3
const __description = 'Prepends mIRC control codes to your text.';
const __default_locale = 'default';

var pluginURL = String(this.plugin.url).replace(/\/[^\/]*$/,'/');
var localeURL = pluginURL + 'locale/' + localeName();
var fallbackLocaleURL = pluginURL + 'locale/' + __default_locale;
var defaultBundle;
var fallbackBundle;

var palette = {white: 0,black: 1,blue: 2,green: 3,red: 4,
    brown: 5,purple: 6,orange: 7,yellow: 8,lightgreen: 9,
    teal: 10,cyan: 11,lightblue: 12,lightpurple: 13,
    gray: 14,lightgray: 15}


var initialprefs = [['code', '']];


plugin.init =
function initPlugin () {
    loadLocale();
    buildPalette();

    plugin.major = __maj_version;
    plugin.minor = __min_version
    plugin.version = plugin.major +'.'+ plugin.minor;
    plugin.description = getMsg ('description');

	if (! ('outputFilters' in client)) { client.outputFilters = new Object(); }
	if (! ('mycolor' in client.outputFilters)) {
		client.outputFilters['mycolor'] = new Object();
	}

	client.outputFilters['mycolor'].func = applycolor;

    //prefs
    plugin.prefary = plugin.prefary.concat(initialprefs);

    //commands
    plugin.cmdlist = [['mycolor',cmdMyColor,null,'[<arg> [<...>]]']];
    client.commandManager.defineCommands(plugin.cmdlist);
    if (plugin.id != getMsg('id')) {
        cmdAlias ({'aliasName': getMsg('id'), 'commandList': 'mycolor'});
    }

    //help
    client.commandManager.commands.mycolor.help = mycolorhelp();

    var startmsg = replaceColorCodes ('%B%C05') + plugin.id;
    if (getMsg('id') != plugin.id) { startmsg += ' ('+ getMsg('id') +')'; }
    startmsg += ' '+ getMsg('version') +' '+ 
        plugin.version +' '+ getMsg('loaded');
    display (startmsg);

}


plugin.enable =
function enablePlugin () {
    plugin.enabled = true;
	client.outputFilters['mycolor'].enabled = true;
    display (getMsg ('enabled'));
    return true;
}


plugin.disable =
function disablePlugin () {
    plugin.enabled = false;
	client.outputFilters['mycolor'].enabled = false;
    display (getMsg ('disabled'));
    return true;
}


function applycolor (msg, msgtype) {
    if (plugin.enabled && plugin.prefs['code'] != '') {
        msg = replaceColorCodes(plugin.prefs['code']) + msg;
    }
    return msg;
}


function cmdMyColor (e) {
    if (e.arg === null) {
        displayMyColor();
        return;
    }
    if (e.arg == '-') {
        plugin.prefs['code'] = '';
        display (getMsg ('reset'));
        return;
    }
    if (e.arg == '-colornames' ||
        e.arg == '-'+getMsg('colornames')) { displayColorNames(); return; }
    //
    //TODO: check if only one arg was provided,
    //TODO: and contains multiple % characters.
    //TODO: if so, treat it as a raw code string.
    //
    //otherwise iterate through e.argList and make color code
    var fg_f=true;
    var fg=null;
    var bg=null;
    var bold=null;
    var underline=null;
    var reverse=null;
    for (var i in e.argList) {
        var j = e.argList[i].toLowerCase();
        var k = colorNumber (j);
        if (k !== null) { j = k; }
        //TODO: strip %c from beginning of string if present.
        //      -- why?
        if (! isNaN(parseInt(j,10))) { 
            j = j % 16;
            if (fg_f) { fg = j; fg_f = false; }
            else { bg = j; }
        }
        else if (j == 'bold' ||
                 j == 'b' || 
                 j == '%b' ||
                 j == getMsg('bold')) { bold = true; }
        else if (j == 'underline' ||
                 j == 'u' ||
                 j == '%u' ||
                 j == getMsg('underline')) { underline = true; }
        else if (j == 'reverse' ||
                 j == 'r' ||
                 j == '%r' ||
                 j == getMsg('reverse')) { reverse = true; }
    }
    //set the pref
    var code=
        (bold === true ? '%B' : '') +
        (underline === true ? '%U' : '') +
        (reverse === true ? '%R' : '') +
        (fg !== null ? '%C'+ (String(fg).length == 1 ? '0' : '') +fg : '') +
        (bg !== null ? ','+ (String(bg).length == 1 ? '0' : '') +bg : '');

    plugin.prefs['code'] = code;
    displayMyColor();


    function displayMyColor() {
        var r = '';
        var code = plugin.prefs['code'];
        if (code.indexOf ('%B') != -1) { r += getMsg('bold')+' '; }
        if (code.indexOf ('%U') != -1) { r += getMsg('underline')+' '; }
        if (code.indexOf ('%R') != -1) { r += getMsg('reverse')+' '; }
        var coloridx = code.indexOf ('%C');
        if (coloridx != -1) {
            var fg_idx = coloridx + 2;
            r += getMsg('color')+': '+ code.substr(fg_idx,2);
            if (code.indexOf(',') != -1) {
                var bg_idx = fg_idx + 3;
                r += ','+ code.substr(bg_idx,2);
            }
        }
        if (r == '') { display (getMsg ('nocodes')); }
        else { display (getMsg ('codes') + r); }
    }

    function colorNumber (name) {
        if (name in palette) {
            return palette[name];
        }
        return null;
    }

    function displayColorNames () {
        var str = '';
        for (var i in palette) {
            str += i +' ';
        }
        display (str);
    }
}


function buildPalette () {
    for (var i in palette) {
        var j = getMsg (i);
        if (j !== null && j != i) {
            palette[j] = palette[i];
        }
    }
}


function mycolorhelp () {
    return getMsg ('help');
}



function localeName () {
    try {
        var cls = '@mozilla.org/chrome/chrome-registry;1';
        var sv = Components.interfaces.nsIXULChromeRegistry;
        var sc = 'global';
        return Components.classes[cls].getService(sv).getSelectedLocale(sc);
    } catch (e) {
        return __default_locale;
    }
}

function loadLocale() {
    try { 
        fallbackBundle = client.messageManager.addBundle (fallbackLocaleURL);
    } catch (e) {
        display ('mycolor plugin: '+ __default_locale +
                 ' locale file required, but not found',MT_ERROR);
        plugin.enabled = false;
        return;
    }
    if (localeURL == fallbackLocaleURL) {
        defaultBundle = fallbackBundle; 
        return;
    }
    try {
        defaultBundle = client.messageManager.addBundle (localeURL);
    } catch (e) {
        defaultBundle = fallbackBundle;
    }
}

function getMsg (name) {
    if (name.indexOf ('.') == -1) {
        name = 'plugin.' + plugin.id + '.' + name;
    }
    var msg = client.messageManager.getMsgFrom (defaultBundle, name, null);
    if (msg == name || msg == null) {
        msg = client.messageManager.getMsgFrom (fallbackBundle, name, null);
    }
    return msg;
}
