import { RES } from "../../module/RES";
import { layers } from "../../module/views/layers";
import Container = FYGE.Container;
import TEXT_ALIGN = FYGE.TEXT_ALIGN;
import TextField = FYGE.TextField;
import Texture = FYGE.Texture;
import Tween = FYGE.Tween;

/**
 * 定制，记录一些全局量和通用方法
 */
export class Tools {

	/**
	 * 缓存key
	 */
	static cacheKey: string = "cow_xiaobujian"

	/************ 其他 ************/
	/**
	 * 修改皮肤上的文本对齐方式，原先默认是左的，多汗行的时候计算有误，待查
	 * @param text
	 * @param align
	 * @param textWidth
	 */
	static changeTextAlign(text: TextField, align: TEXT_ALIGN, textWidth?: number) {
		if (align == TEXT_ALIGN.LEFT) return;
		text.textAlign = align;
		//没有就原先的
		textWidth = textWidth || text.textWidth;
		//修改位置
		if (align == TEXT_ALIGN.CENTER) text.x -= (textWidth - text.textWidth) / 2;
		if (align == TEXT_ALIGN.RIGHT) text.x -= textWidth - text.textWidth
		text.textWidth = textWidth;
	}

	/**
	 * 延时防连点
	 * @param target
	 * @param {number} delay 默认2000毫秒
	 */
	static btnDelay(target: Container, delay: number = 2000) {
		target.mouseEnable = false;
		target.mouseChildren = false;
		setTimeout(() => {
			target.mouseEnable = true;
			target.mouseChildren = true;
		}, delay);
	}

	/**
	 * 根据名字获取0到9的贴图
	 * 位图字每次都写太烦了
	 * @param name
	 */
	static getNumTextures(name: string): { [key: number]: Texture } {
		const arr = {};
		for (let i = 0; i <= 9; i++) arr[i] = RES.getRes(name + i + ".png")
		return arr
	}

	/**
	 * 获得距离底部的百分比高度，还要减个自身的高度，自行处理
	 * @param {number} percent  百分比
	 * @returns {number}
	 */
	static getAdjustBottomHeight(percent: number): number {
		return layers.stageHeight - layers.stageHeight * percent + layers.stageOffsetY;//stageOffsetY加不加取决于页面适配类型
	}

	/**
	 * 获得距离顶部的百分比高度
	 * @param {number} percent  百分比
	 * @returns {number}
	 */
	static getAdjustTopHeight(percent: number): number {
		return layers.stageHeight * percent + layers.stageOffsetY;//stageOffsetY加不加取决于页面适配类型
	}

}


/**
 * 从数组里随机取元素
 * @param arr
 * @param count
 */
export function getRandomArrayElements(arr, count) {
	if (arr.length <= count) return arr;

	let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
	while (i-- > min) {
		index = (i + 1) * Math.random() >> 0;
		temp = shuffled[index];
		shuffled[index] = shuffled[i];
		shuffled[i] = temp;
	}
	return shuffled.slice(min);
}


/**
 * 数字补0
 * @param num 数字
 * @param length 位数
 */
export function prefixInteger(num: number, length: number) {
	return (Array(length).join('0') + num).slice(-length);
}


export function numLimit(num: number, min: number, max: number): number {
	if (num > max) return max;
	else if (num < min) return min;
	return num;
}

export async function sleep(time: number): Promise<void> {
	return new Promise((resolve) => {
		Tween.get(FYGE)
			.wait(time)
			.call(resolve)
	});
}
