package it.gotoandplay.smartfoxclient.handlers;

import it.gotoandplay.smartfoxclient.SFSEvent;
import it.gotoandplay.smartfoxclient.SmartFoxClient;
import it.gotoandplay.smartfoxclient.data.SFSObject;
import it.gotoandplay.smartfoxclient.util.SFSObjectSerializer;
import net.n3.nanoxml.IXMLElement;
import org.json.JSONObject;

/*
 * ExtHandler class.
 * 
 * @version 1.0.0
 * 
 * @author The gotoAndPlay() Team<br>
 *         <a href="http://www.smartfoxserver.com">http://www.smartfoxserver.com</a><br>
 *         <a href="http://www.gotoandplay.it">http://www.gotoandplay.it</a><br>
 */
public class ExtHandler implements IMessageHandler
{
    private SmartFoxClient sfs;

    public ExtHandler(SmartFoxClient sfs)
    {
        this.sfs = sfs;
    }
		
    /*
     * Handle messages
     */
    public void handleMessage(Object msgObj, String type)
    {
        SFSObject params;
        SFSEvent evt;

        if(type.equals(SmartFoxClient.XTMSG_TYPE_XML))
        {
            IXMLElement xmlData = (IXMLElement)msgObj;
            IXMLElement body = xmlData.getFirstChildNamed("body");
            String action = body.getAttribute("action", "");

            if(action.equals("xtRes"))
            {
		SFSObject asObj = SFSObjectSerializer.deserialize(body.getContent());

		// Fire event!
		params = new SFSObject();
		params.put("dataObj", asObj);
		params.put("type", type);

		evt = new SFSEvent(SFSEvent.onExtensionResponse, params);
		sfs.dispatchEvent(evt);
            }
        }
        else if(type.equals(SmartFoxClient.XTMSG_TYPE_JSON))
        {
            // Fire event!
            params = new SFSObject();
            JSONObject dataObj = ((JSONObject)msgObj).optJSONObject("o");
            params.put("dataObj", dataObj);
            params.put("type", type);

            evt = new SFSEvent(SFSEvent.onExtensionResponse, params);
            sfs.dispatchEvent(evt);
        }
        else if(type.equals(SmartFoxClient.XTMSG_TYPE_STR))
        {
            // Fire event!
            params = new SFSObject();
            params.put("dataObj", msgObj);
            params.put("type", type);

            evt = new SFSEvent(SFSEvent.onExtensionResponse, params);
            sfs.dispatchEvent(evt);
        }
    }
}
