package projectzombie.tiles;

import gl_engine.MathHelpers;
import gl_engine.vec.Vec2i;
import gl_engine.vec.Vec3d;
import projectzombie.entity.Entity;
import projectzombie.entity.particle.ParticleSmoke;
import projectzombie.entity.tileentity.TileEntityCampfire;
import projectzombie.init.Models;
import projectzombie.init.Tiles;
import projectzombie.inventory.Inventory;
import projectzombie.items.ItemTool;
import projectzombie.items.ItemToolType;
import projectzombie.model.Model;
import projectzombie.util.ItemStack;
import projectzombie.util.TileState;
import projectzombie.world.chunk.Chunk;
import projectzombie.world.layer.Layer;

public class TileCampfire extends Tile
{

	public TileCampfire() {
		this.emitsLight = true;
		this.tileSolid = true;
		this.tileHitbox = 0.5;
		this.hardness = 800;
	}
	
	@Override
	public double getLightLevel(TileState state, Vec2i pos) {
		return 1 - MathHelpers.squared(1 - state.meta / 16.0);
	}
	
	@Override
	public Model getModel(byte meta) {
		return meta == 0 ? Models.TILE_CAMPFIRE_UNLIT : Models.TILE_CAMPFIRE_LIT;
	}
	
	@Override
	public void tickRandomly(Layer layer, Chunk chunk, TileState state, Vec2i pos)
	{
		super.tickRandomly(layer, chunk, state, pos);
		
		if(state.meta != 0) {
			chunk.spawnEntity(new ParticleSmoke(new Vec3d(pos.x + 0.5, 0, pos.y + 0.5), new Vec3d(0, 0, 0)));
		}
	}
	
	@Override
	public boolean onActivated(Layer layer, Vec2i tpos, Entity entity, TileState state) {
		super.onActivated(layer, tpos, entity, state);
		
		TileEntityCampfire te = (TileEntityCampfire)layer.getTileEntity(tpos);
		
		if(!(te instanceof TileEntityCampfire)) {
			te = new TileEntityCampfire(tpos);
			layer.createTileEntity(tpos, te);
		}
		
		te.onOpened();
		
		return true;
	}
	
	@Override
	public boolean canTileBreak(TileState state, ItemStack stack, ItemTool tool) {
		return true;
	}
	
	@Override
	public boolean canTileSpeedBreak(TileState state, ItemStack stack, ItemTool tool) {
		return (tool != null && tool.toolType(stack) == ItemToolType.HATCHET);
	}

	@Override
	public void onDestroy(Layer layer, Chunk chunk, TileState oldState, TileState newState, Vec2i pos) {
		super.onDestroy(layer, chunk, oldState, newState, pos);
		
		if(newState.tile == Tiles.CAMPFIRE) {
			return;
		}
		
		TileEntityCampfire te = (TileEntityCampfire)chunk.getTileEntity(pos);
		
		if(te != null) {
			te.getInventory().dropInventory(layer, chunk, pos.toDouble().add(0.5).xny(), new Vec3d(0, 0, 0));
		}
		
		chunk.destroyTileEntity(pos);
		
		System.out.println("Campfire destroyed");
	}
	
}
