/**
 * Created by rockyl on 2018/7/12.
 */

import Bounds from "../support/Bounds";
import HashObject from "../core/HashObject";
import {createCanvas} from "./context/RenderContext";

/**
 * 纹理类
 */
export default class Texture extends HashObject {
	img: any;
	bounds: Bounds;

	_cacheCanvas;

	constructor() {
		super();

		this.bounds = new Bounds();
	}

	/**
	 * 设置图集中的坐标和尺寸
	 * @param frame
	 */
	setFrame(frame) {
		let {x, y, w, h} = frame;
		this.bounds.setTo(x, y, w, h);
	}

	/**
	 * 设置图片
	 * @param img
	 */
	setImg(img) {
		this.img = img;
	}

	/**
	 * 获取纹理宽度
	 */
	get width() {
		return this.bounds.width;
	}

	/**
	 * 获取纹理高度
	 */
	get height() {
		return this.bounds.height;
	}

	/**
	 * 产生一个缓存画布
	 */
	getCacheCanvas() {
		const {width, height} = this.bounds;

		let canvas = this._cacheCanvas;
		if (!canvas) {
			canvas = this._cacheCanvas = createCanvas();
		}
		canvas.width = width;
		canvas.height = height;

		const context = canvas.getContext('2d');
		this.drawToCanvas(context);

		return canvas;
	}

	/**
	 * 绘制到一个画布上
	 * @param context
	 * @param dx
	 * @param dy
	 * @param sx
	 * @param sy
	 * @param dw
	 * @param dh
	 */
	drawToCanvas(context, dx = 0, dy = 0, sx?, sy?, dw?, dh?) {
		const {x, y, width, height} = this.bounds;
		context.drawImage(this.img, sx || x, sy || y, width, height, dx, dy, dw || width, dh || height);
	}

	/**
	 * 销毁自身
	 */
	destroy() {
		this.img = null;
		this.bounds = null;

		this.destroyCacheCanvas();
	}

	/**
	 * 销毁缓存画布
	 */
	destroyCacheCanvas(){
		this._cacheCanvas = null;
	}
}

/**
 * 快捷创建纹理
 * @param img
 * @param frame
 */
export function createTexture(img, frame?): Texture {
	const texture = new Texture();
	texture.setImg(img);
	texture.setFrame(frame || {x: 0, y: 0, w: img.width, h: img.height});

	return texture;
}
