import { Button, Sprite, view, Node, ScrollView, Vec2, Vec3, TiledLayer, Size } from "cc";
import List from "../list/List";

export class UIHelper {

    //将一个按钮置灰
    static buttonEnable(button: Button, enable: boolean) {
        if (button) {
            let sprite = button.getComponent(Sprite);
            (sprite) && (sprite.grayscale = !enable);
            button.interactable = enable;
        }
    }

    //获取设计分辨率
    static getDesignSize() {
        return view.getDesignResolutionSize();
    }

    //设置节点layer
    static setLayer(node: Node, layer: number) {
        if (node) {
            node.layer = layer;
            node.walk((child) => {
                child.layer = layer;
            });
        }
    }

    //销毁一个List或者是ScrollView
    static destroyList(view: List | ScrollView, name: any) {
        if (view) {
            view.node.active = true;
            for (let child of view.content.children) {
                let comp = child.getComponent(name);
                if (comp && comp["onClose"]) {
                    let callback: Function = comp["onClose"];
                    callback.apply(comp);
                }
            }
            view.node.destroy();
            view = null;
        }
    }

    //将OpenGL坐标转为Tiledmap坐标
    static openGLToTiled(pos: Vec3, map_size: Size, tile_size: Size) {
        let out = new Vec2();
        if (pos && map_size && tile_size) {
            out.x = Math.floor(pos.x / tile_size.width);
            out.y = Math.floor((map_size.height * tile_size.height - pos.y) / tile_size.height);
        }
        return out;
    }

    //将Tiledmap坐标转为OpenGL坐标
    static tiledToOpenGL(pos: Vec3, map_size: Size, tile_size: Size) {
        let out = new Vec2();
        if (pos && map_size && tile_size) {
            out.x = pos.x * tile_size.width + tile_size.width / 2;
            out.y = (map_size.height - pos.y) * tile_size.height - tile_size.height / 2;
        }
        return out;
    }
}