import { _decorator, Component, v3, instantiate, Label, math, Node, Prefab, tween, UIOpacity } from "cc";
import { MainGame } from "../MainGame";
import { Snake } from "../Snake";

const { ccclass, property } = _decorator;

@ccclass("Rank")
export class Rank extends Component {

    @property(Prefab) otherRankPrefab: Prefab;
    @property(Prefab) selfRankPrefab: Prefab;

    @property(Node) selfNode: Node;

    nodeMap = new Map<number, Node>();

    start() {
        this.nodeMap.clear();
        this.nodeMap.set(MainGame.ins.player.tag, this.selfNode);

        this.schedule(() => {
            this.updateRank();
        }, 1);
    }

    updateRank() {
        const snakes = MainGame.ins.animalNode.children.map((snakeNode) => {
            const snake = snakeNode.getComponent(Snake);
            if (!this.nodeMap.has(snake.tag)) {
                const node = instantiate(this.otherRankPrefab);
                node.position.set(0, -220 - 44);
                node.getComponent(UIOpacity).opacity = 0;
                node.getChildByName("nick").getComponent(Label).string = snake.nickName;
                this.node.addChild(node);
                this.nodeMap.set(snake.tag, node);
            }
            return snake;
        });

        snakes.push(MainGame.ins.player);
        snakes.sort((a, b) => {
            return b.length - a.length;
        });

        const playerIndex = snakes.indexOf(MainGame.ins.player);

        for (let i = 0; i < snakes.length; i++) {

            const node = this.nodeMap.get(snakes[i].tag);
            node.getChildByName("rank").getComponent(Label).string = `${i + 1}`;

            let rankIndex = i;
            if (i == playerIndex) {
                rankIndex = Math.min(rankIndex, 5);
            } else if (playerIndex > 5 && rankIndex >= 5) {
                rankIndex = 7;
            }

            tween(node)
                .to(0.288, { position: v3(0, -44 * rankIndex, 0) })
                .start();

            tween(node.getComponent(UIOpacity))
                .to(0.288, { opacity: rankIndex > 5 ? 0 : 255 })
                .start();

        }

    }

    update(deltaTime: number) {

    }
}


