
import * as cc from "cc";
export default class cp_palette_util {

    public static get_rgba_arr(h: number, s: number, l: number, a: number = 255) {
        let color = new cc.Color().fromHSV(h, s, l);

        let r = color.r;
        let g = color.g;
        let b = color.b;
        // let a = color.a;
        return [r, g, b, a];
    }

    public static get_rgba(color: cc.Color) {
        let r = color.r;
        let g = color.g;
        let b = color.b;
        let a = color.a;
        return { r, g, b, a };
    }

    public static get_rgba_arr_by_color(color: cc.Color) {
        let r = color.r;
        let g = color.g;
        let b = color.b;
        let a = color.a;
        return [r, g, b, a];
    }

    public static unit8array_to_texture2d(arr: Uint8Array, width: number, height: number): cc.Texture2D {
        let tex = new cc.Texture2D();
        const image = new cc.ImageAsset({
            _data: arr,
            _compressed: false,
            width: width,
            height: height,
            format: cc.Texture2D.PixelFormat.RGBA8888,
        });
        const texture = new cc.Texture2D();
        texture.setFilters(cc.Texture2D.Filter.NEAREST, cc.Texture2D.Filter.NEAREST);
        texture.image = image;
        return texture;
    }

    public static grid_to_texture2d(
        grid: Array<Array<number>>,
        width: number, height: number,
    ): cc.Texture2D {
        // let arr = grid.reduce((a, b) => { return a.concat(b); });
        let data = null;
        data = new Uint8Array(grid.length * 4);
        let index = 0;
        let obj = grid[index];
        let count = 0;
        for (let i = 0; i < data.length; i += 4) {
            obj = grid[i / 4];
            data[i] = obj[0];
            data[i + 1] = obj[1];
            data[i + 2] = obj[2];
            data[i + 3] = obj[3];
        }
        let tex = this.unit8array_to_texture2d(data, width, height);
        // console.timeEnd("2d")
        return tex;
    }

    /**
     * 网格RGBA数组转Texture2D
     * @param grid 
     * @param size 
     * @returns 
     */
    public static grid2SpriteFrame(grid: Array<Array<number>>, width: number, height: number): cc.SpriteFrame {
        //反转y轴，因为图片是从左下角作为其实坐标
        grid.reverse();
        let arr = [];
        for (let y = 0; y < grid.length; y++) {
            arr.push(...grid[y]);
        }
        const sp = new cc.SpriteFrame();
        sp.texture = this.grid_to_texture2d(arr, width, height);
        sp.packable = false;
        return sp;
    }


}