package net.sourceforge.pain.plugin.social;
import net.sourceforge.pain.*;
import net.sourceforge.pain.plugin.*;
import net.sourceforge.pain.plugin.command.*;
import net.sourceforge.pain.util.*;
import java.io.*;
import java.util.*;
/**
 * this plugin adds socials to game. Socials area registered after commands so have a lower priority
 * net.sourceforge.pain.logic.event.Social is used with this plugin
 */
public final class SocialPlugin extends Plugin {
	Map socials = new HashMap();
	CommandMapper commandMapper;
	public void init() throws Exception {
		Log.debug("Socials Plug INIT");
		commandMapper = (CommandMapper) loader.plm.getPlugin("command.CommandMapper"); //dependency will be added automatically
		if (commandMapper  == null) {
			throw new RuntimeException("CommandMapper plugin is not loaded!");
		}
		loadSocials();
		Log.debug("Socials Plug INIT OK");
	}
	public void deinit() {
		Log.debug("Socials Plug DEINIT");
		removeCommandMapping();
		Log.debug("Socials Plug DEINIT OK");
	}
	public SocialEntry getSocial(String name) {
		return (SocialEntry) socials.get(name);
	}
	private void loadSocials() throws Exception {
		socials = new HashMap();
		String fileName = Core.getApplicationPath() + "/etc/socials.cfg";
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		SocialParser parser = new SocialParser();
		try {
			Collection c = parser.parseSocials(reader);
			Log.debug("Socials parsed OK");
			for (Iterator it = c.iterator(); it.hasNext();) {
				SocialEntry entry = (SocialEntry) it.next();
				commandMapper.registerCommand(entry.tag, "SocialHandler", entry.tag);
				socials.put(entry.tag, entry);
			}
		} finally {
			reader.close();
		}
	}
	private void removeCommandMapping() {
		for (Iterator it = socials.values().iterator(); it.hasNext();) {
			commandMapper.unregisterCommand(((SocialEntry) it.next()).tag);
		}
		socials.clear();
	}
}