package com.homiedion.rpgcore.container.race;

import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;

import com.homiedion.aeoncore.type.TypeManager;
import com.homiedion.rpgcore.RpgCore;
import com.homiedion.rpgcore.RpgPlugin;

/**
 * A container for the RpgRace.
 *
 * @author HomieDion
 * @since 1.0.0
 * @version 1.0.0
 */
public class RpgRaceManager extends TypeManager {
	/**
	 * The plugin's logger.
	 *
	 * @author HomieDion
	 * @since 1.0.0
	 */
	private final Logger log = RpgCore.getInstance().getLogger();

	/**
	 * Default Constructor
	 *
	 * @author HomieDion
	 * @since 1.0.0
	 */
	public RpgRaceManager() {
		super();
	}

	/**
	 * Returns an RpgRace if it is present.
	 *
	 * @author HomieDion
	 * @since 1.0.0
	 * @param key
	 *            The target key.
	 * @return An RpgRace or null.
	 */
	public RpgRace get(final String key) {
		if (!isRegistered(key)) {
			return null;
		}
		return (RpgRace) getType(key);
	}

	/**
	 * Used to register types for this manager.
	 *
	 * @author HomieDion
	 * @since 1.0.0
	 */
	public void register() {
		// Variables
		final int loggingLevel = RpgCore.getInstance().getPluginSettings().getLoggingLevel();

		// Loop all plugins present.
		for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
			// If this is an RpgPlugin
			if (plugin instanceof RpgPlugin) {
				// Trigger
				try {
					((RpgPlugin) plugin).registerRaces();
				} catch (final Exception e) {
					if (loggingLevel >= 1) {
						log.warning("Failed to register races from \"" + plugin.getName() + "\"! Is it up to date?");
					}
					
					if (loggingLevel == 2) {
						log.severe(e.getCause().toString());
					}
					
					if (loggingLevel >= 3) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * Registers the type under its name.
	 *
	 * @author HomieDion
	 * @since 1.0.0
	 * @param type
	 *            The type we're registering.
	 * @return True if successful.
	 */
	public boolean register(final RpgRace type) {
		// Variables
		final int loggingLevel = RpgCore.getInstance().getPluginSettings().getLoggingLevel();

		if (register(type.getName(), type)) {
			if (loggingLevel >= 2) {
				log.info("Successfully registered race \"" + type.getName() + "\"");
			}
			return true;
		} else {
			if (loggingLevel >= 1) {
				log.warning("Failed to register race \"" + type.getName() + "\"");
			}
			return false;
		}
	}
}
