package org.egordorichev.lasttry.world.components;

import org.egordorichev.lasttry.Globals;
import org.egordorichev.lasttry.item.Item;
import org.egordorichev.lasttry.item.ItemID;
import org.egordorichev.lasttry.item.block.Block;
import org.egordorichev.lasttry.world.World;
import org.egordorichev.lasttry.world.chunk.Chunk;

public class WorldBlocksComponent extends WorldComponent {
	public WorldBlocksComponent(World world) {
		super(world);
	}

	//grid points
	public Block get(int x, int y) {
		return (Block) Item.fromID(this.getID(x, y));
	}

	public short getID(int x, int y) {
		Chunk chunk = this.getChunk(x, y);

		if (chunk == null) {
			return ItemID.none;
		}

		return chunk.getBlock(x, y);
	}

	public void set(short id, int x, int y) {
		Chunk chunk = this.getChunk(x, y);

		if (chunk == null) {
			return;
		}

		chunk.setBlock(id, x, y);
	}

	public byte getHP(int x, int y) {
		Chunk chunk = this.getChunk(x, y);

		if (chunk == null) {
			return Block.MAX_HP;
		}

		return chunk.getBlockHP(x, y);
	}

	public void setHP(byte hp, int x, int y) {
		Chunk chunk = this.getChunk(x, y);

		if (chunk == null) {
			return;
		}


		chunk.setBlockHP(hp, x, y);
	}

	private Chunk getChunk(int x, int y) {
		if (!this.world.isInside(x, y)) {
			return null;
		}

		Chunk chunk = this.world.chunks.getFor(x, y);

		if (chunk == null) {
			Globals.world.chunks.load(x / Chunk.SIZE, y / Chunk.SIZE);
			return null;
		}

		return chunk;
	}
}
@@ -447,16 +447,17 @@
 %0A%09%7D%0A%0A%09//
+ 
 grid poi
@@ -460,16 +460,17 @@
  points%0A
+%0A
 %09public 
@@ -851,24 +851,54 @@
 (id, x, y);%0A
+%09%09this.updateNeighbors(x, y);%0A
 %09%7D%0A%0A%09public 
@@ -1172,17 +1172,16 @@
 n;%0A%09%09%7D%0A%0A
-%0A
 %09%09chunk.
@@ -1197,24 +1197,77 @@
 P(hp, x, y);
+%0A%0A%09%09if (hp == 0) %7B%0A%09%09%09this.updateNeighbors(x, y);%0A%09%09%7D
 %0A%09%7D%0A%0A%09privat
@@ -1507,24 +1507,24 @@
  null;%0A%09%09%7D%0A%0A
-
 %09%09return chu
@@ -1529,10 +1529,267 @@
 hunk;%0A%09%7D
+%0A%0A%09private void updateNeighbors(int x, int y) %7B%0A%09%09for (int by = y - 1; by %3C y + 2; by++) %7B%0A%09%09%09for (int bx = x - 1; bx %3C x + 2; bx++) %7B%0A%09%09%09%09Block block = this.get(bx, by);%0A%0A%09%09%09%09if (block != null) %7B%0A%09%09%09%09%09block.onNeighborChange(bx, by, x, y);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D
 %0A%7D

Update neighbors