package org.spacehq.openclassic.api.block;

import com.zachsthings.onevent.EventManager;
import org.apache.commons.lang3.Validate;
import org.spacehq.openclassic.api.event.block.BlockRegisterEvent;
import org.spacehq.openclassic.api.event.block.BlockUnregisterEvent;

import java.util.Arrays;
import java.util.List;

/**
 * The block registry.
 */
public class Blocks {
	
	private static final BlockType registry[] = new BlockType[256];
	
	/**
	 * Gets the block with the given ID.
	 * @param id ID of the block.
	 * @return The block with the given ID.
	 */
	public static BlockType fromId(int id) {
		if(id < 0) {
			return null;
		}
		
		return registry[id];
	}
	
	/**
	 * Registers a block.
	 * @param block Block to register.
	 */
	public static void register(BlockType block) {
		Validate.notNull(block, "Block cannot be null.");
		EventManager.callEvent(new BlockRegisterEvent(block));
		registry[block.getId()] = block;
	}
	
	/**
	 * Unregisters a block.
	 * @param block Block to unregister.
	 */
	public static void unregister(BlockType block) {
		Validate.notNull(block, "Block cannot be null.");
		EventManager.callEvent(new BlockUnregisterEvent(block));
		registry[block.getId()] = null;
	}
	
	/**
	 * Gets a list of all the blocks.
	 * @return A list of blocks.
	 */
	public static List<BlockType> getBlocks() {
		return Arrays.asList(registry);
	}
	
}
