/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JIM.
 *
 * The Initial Developer of the Original Code is
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * scripts.uiscripts.UserList
 *
 *
 */
ML.load("xml/xmldombuilder.js");

function UserListHandler()
{
    this.bundle = getStringBundle("chrome://jim/locale/jim.properties");
}

UserListHandler.prototype =
{
    onLoad: function()
    {
        var popup = document.getAnonymousElementByAttribute(this.list, 
            'anonid', 'groups-popup');
        var thisObj = this;

        this.list.content.database.AddDataSource(jabberService.localRDF.DS);
        this.list.content.builder.rebuild();
        popup.database.AddDataSource(jabberService.localRDF.DS);
        popup.builder.rebuild();
    },

    onBaseToolTipShowing: function(event, el)
    {
        var i, attrs;
        var idattr, popsattr;
        
        if (el.contextParent == window.contextParent)
            return;

        el.contextParent = window.contextParent;

        while (el.firstChild)
            el.removeChild(el.firstChild);

        idattr = el.getAttributeNode("id");
        popsattr = el.getAttributeNode("onpopupshowing");

        for (i = el.attributes.length-1; i >= 0; i--)
            el.removeAttributeNode(el.attributes[i]);

        el.setAttributeNode(idattr);
        el.setAttributeNode(popsattr);

        node = window.contextParent.getElementsByTagName("tooltip")[0];

        for (i = 0; i < node.attributes.length; i++)
            el.setAttribute(node.attributes[i].nodeName, node.attributes[i].nodeValue);

        node = node.firstChild;
        while (node) {
            el.appendChild(node.cloneNode(true));
            node = node.nextSibling;
        }
    },

    onPopupUserShowing: function(event, el)
    {
        this.contextParent = window.contextParent;
    },

    onGroupClick: function(event, _this)
    {
        var target = event.currentTarget;

        target.parentNode.setAttribute("group-collapsed", 
            target.parentNode.getAttribute("group-collapsed") == "true" ?
                "false" : "true");
    },

    onNameEditEnd: function(event)
    {
        var target = event.currentTarget;
        var jid = target.getAttribute("jid");
        var user = jabberService.localRDF.getResource(
            jabberService.core.highlevel.users.getUserIDByJID(jid));
        var it, groups = [];

        jabberService.localRDF.ns = JIM_NAMESPACE_URI+"rdf/users#";
        it = user.getTarget("user-groups").getElements();

        while (it.hasNext())
            groups.push(it.getNext().getTarget("group-name").value);

        target.parentNode.selectedIndex = 0;

        jabberService.core.iq.roster.addItem(jid, target.value,
            groups);
    },

    onEditUser: function(event)
    {
        var deck = this.contextParent.getElementsByTagName("deck")[0];
        deck.selectedIndex = 1;
        deck.childNodes[1].focus();
    },

    onRemoveUser: function(event)
    {
        var target = event.currentTarget;
        var jid = this.contextParent.getAttribute("shortjid");

        if (window.confirm(this.bundle.
            GetStringFromName("userListRemoveUserAsk")))
        {
    
            jabberService.localRDF.ns = JIM_NAMESPACE_URI+"rdf/users#";
            jabberService.core.iq.roster.removeItem(jid);
        }
    },

    onUserInfo: function(event)
    {
        var jid = this.contextParent.getAttribute("shortjid");
        var win = this.getWindowSpec("jim:vcard", jid);

        if (win)
            win.focus();
        else
            openDialog("chrome://jim/content/vcard.xul", 
                "_blank", "chrome,all,dialog=no", jid);
    },

    onChangeGroup: function(event)
    {
        var target = event.currentTarget;
        var jid = this.contextParent.getAttribute("shortjid");
        var user = jabberService.localRDF.getResource(
            jabberService.core.highlevel.users.getUserIDByJID(jid));

        jabberService.localRDF.ns = JIM_NAMESPACE_URI+"rdf/users#";

        jabberService.core.iq.roster.addItem(jid, 
            user.getTarget("user-name").value, target.getAttribute("label"));
    },

    onNewGroup: function(event)
    {
        var jid = this.contextParent.getAttribute("shortjid");
        var user = jabberService.localRDF.getResource(
            jabberService.core.highlevel.users.getUserIDByJID(jid));
        var group = window.prompt(this.bundle.
            GetStringFromName("userListNewGroupAsk"));

        if (!group)
            return;

        jabberService.localRDF.ns = JIM_NAMESPACE_URI+"rdf/users#";

        jabberService.core.iq.roster.addItem(jid, 
            user.getTarget("user-name").value, group);
    },

    onChat: function(jid)
    {
        this.openChatWindow(jid);
    },

    onSendAuthorisation: function(event)
    {
        var jid = this.contextParent.getAttribute("shortjid");

        jabberService.core.subscribed(jid);
    },

    onRequestAuthorisation: function(event)
    {
        var jid = this.contextParent.getAttribute("shortjid");

        jabberService.core.subscribe(jid,
            this.bundle.GetStringFromName("addContactSubscribeText"));
    },

    onRemoveAuthorisation: function(event)
    {
        var jid = this.contextParent.getAttribute("shortjid");

        jabberService.core.unsubscribed(jid);
    },

    onUserDblClick: function(event)
    {
        var target = event.currentTarget;

        var jid = target.getAttribute("jid");
        this.onChat(jid);
        event.stopPropagation();
    },

    onResourceDblClick: function(event)
    {
        var target = event.currentTarget;

        this.openChatWindow(target.getAttribute("jid"));

        event.stopPropagation();
    },

    openChatWindow: function(jid)
    {
        var win = this.getWindowSpec("jim:chat", jid);

        if (win)
            win.focus();
        else
            openDialog("chrome://jim/content/chat.xul", 
                "_blank", "chrome,all,dialog=no", jid);
    },

    getWindowSpec: function(type, contact)
    {
        var wmediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].
            getService(Components.interfaces.nsIWindowMediator);
        var it, win;

        it = wmediator.getEnumerator(type);

        while (it.hasMoreElements()) {
            win = it.getNext();
            if (win.contact == contact)
                return win;
        }
        return null;
    },

    onDragStart: function(evt, transferData, action)
    {
        var txt = evt.target.getAttribute("jid");
        transferData.data=new TransferData();
        transferData.data.addDataForFlavour("text/x-jabberid",txt);
    },

    getSupportedFlavours: function()
    {
        var flavours = new FlavourSet();
        flavours.appendFlavour("text/x-jabberid");
        return flavours;
    },

    onDragOver: function(evt,flavour,session)
    {
        evt.currentTarget.setAttribute("dragtarget", "true");
    },

    onDragExit: function(evt,flavour,session)
    {
        evt.currentTarget.removeAttribute("dragtarget");
    },

    onDrop: function(evt, dropdata, session)
    {
        var user, group;

        if (dropdata.data != "") {
            user = jabberService.core.highlevel.users.
                getUserIDByJID(dropdata.data);

            if (!user)
                return;

            jabberService.localRDF.ns = JIM_NAMESPACE_URI+"rdf/users#";

            user = jabberService.localRDF.getResource(user).
                getTarget("user-name").value;

            if (evt.currentTarget.getAttribute("class") == "groups")
                setTimeout(this.__onDrop, 0, this, dropdata.data,
                    user, null, true);
            else
                this.__onDrop(this, dropdata.data, user, 
                    evt.currentTarget.getAttribute("group-name"), false);
        }
    },

    __onDrop: function(_this, jid, user, group, askGroup)
    {
        if (askGroup)
            group = window.prompt(_this.bundle.
                GetStringFromName("userListNewGroupAsk"));

        if (group) {
            jabberService.core.iq.roster.addItem(jid, user, group);
        }
    },
}

var userListHandler = new UserListHandler();