class Tile extends E {
	tileWidth:number;
	tileHeight:number;
	image: HTMLImageElement;
	canvas: HTMLCanvasElement;
	data: number[][];
	sep:number;
	chipCount:CommonSize;

	constructor(tileWidth:number, tileHeight:number, image?:HTMLImageElement) {
		super();
		this.tileWidth = tileWidth;
		this.tileHeight = tileHeight;
		this.image = image;
		this.x = 0;
		this.y = 0;
		this.sep = Math.floor(this.image.width / this.tileWidth);
		this.disableTransform = true;
	}

	generate(data:number[][], width?:number, height?:number) {
		this.data = data;
		if (! width)
			width = this.data.length;
		if (! height)
			height = this.data[0].length;
		this.chipCount = {
			w: width,
			h: height
		}
		this.width = this.tileWidth * width;
		this.height = this.tileHeight * height;
		this.refresh();
	}

	refresh() {
		this.canvas = window.createCanvas(this.width, this.height);
		var c = this.canvas.getContext("2d");

		for (var x=0; x<this.chipCount.w; x++) {
			for (var y=0; y<this.chipCount.h; y++) {
				c.drawImage(
					this.image,
					(this.data[x][y] % this.sep) * this.tileWidth,
					Math.floor(this.data[x][y] / this.sep) * this.tileHeight,
					this.tileWidth,
					this.tileHeight,
					x * this.tileWidth,
					y * this.tileHeight,
					this.tileWidth,
					this.tileHeight
				);
			}
		}
	}

	createSprite(area:Area):Sprite {
		var canvas:HTMLCanvasElement = window.createCanvas(area.width, area.height);
		var context = canvas.getContext("2d");
		context.drawImage(
			this.canvas,
			area.x,
			area.y,
			area.width,
			area.height,
			0,
			0,
			area.width,
			area.height
		);
		return new Sprite(area.width, area.height, canvas);
	}

	draw(area:Area, context:CanvasRenderingContext2D) {
		var src:Area = new Area(-area.x, -area.y, area.width, area.height);
		var dist:Area = new Area(0, 0, area.width, area.height);
		if (src.x < 0) {
			src.width += src.x;
			if (src.width <= 0)
				return;
			dist.x -= src.x;
			dist.width += src.x;
			src.x = 0;
		} else if ((src.x+src.width) > this.width) {
			var p = ((src.x+src.width) - this.width);
			src.width -= p;
			if (src.width <= 0)
				return;
			dist.width -= p;
		}
		if (src.y < 0) {
			src.height += src.y;
			if (src.height <= 0)
				return;
			dist.y -= src.y;
			dist.height += src.y;
			src.y = 0;
		} else if ((src.y+src.height) > this.height) {
			var p = ((src.y+src.height) - this.height);
			src.height -= p;
			if (src.height <= 0)
				return;
			dist.height -= p;
		}

		context.drawImage(
			this.canvas,
			src.x,
			src.y,
			src.width,
			src.height,
			dist.x,
			dist.y,
			dist.width,
			dist.height
		);
	}
}