/**
 * Created by rockyl on 2018-11-30.
 */

import HashObject from "../core/HashObject";
import {createTexture} from "./Texture";

/**
 * 图集
 */
export class Sheet extends HashObject{
	/**
	 * 图集原图
	 */
	img: any;
	/**
	 * 图集分割配置
	 */
	frames: any;

	private _textureCache: any = {};

	constructor(img?, frames?) {
		super();

		if(img){
			this.img = img;
		}
		if(frames){
			this.frames = frames;
		}
	}

	/**
	 * 生成全部纹理
	 */
	generateAll() {
		for (let key in this.frames) {
			this.generateTexture(key);
		}
	}

	/**
	 * 生成一个纹理
	 * @param name
	 * @param force
	 */
	generateTexture(name, force = false) {
		const {img, frames, _textureCache} = this;

		if (!force && _textureCache[name]) {
			return _textureCache[name];
		}

		const frame = frames[name];
		if (frame) {
			return _textureCache[name] = createTexture(img, frame);
		}
	}

	/**
	 * 是否有这个纹理
	 * @param name
	 */
	hasTexture(name) {
		return !!frames[name];
	}

	/**
	 * 获取纹理
	 * @param name
	 */
	getTexture(name) {
		let texture = this._textureCache[name];
		if (texture) {
			return texture;
		} else {
			return this.generateTexture(name);
		}
	}

	/**
	 * 获取全部存在的纹理
	 */
	getAllTextures() {
		return this._textureCache;
	}

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

		for (let key in this._textureCache) {
			this._textureCache[key].destroy();
			delete this._textureCache[key];
		}
	}
}
