import { Runner } from "./Runner";
import { EventManager, EventType } from "./EventManager";
import { GameState } from "./GameManager";

export class Queue 
{
    private static instance:Queue;
    constructor()
    {
        Queue.instance = this;
        this.InitQueue();
    }
    public static get Instance():Queue
    {
        if(Queue.instance)
        {
            return Queue.instance;
        }
        else
        {
            return new Queue();
        }
    }

    InitQueue()
    {
        EventManager.GameStateEventOn(GameState.Win,this,this.OnGameEnd);
        EventManager.GameStateEventOn(GameState.End,this,this.OnGameOver);
        EventManager.GameStateEventOn(GameState.Playing,this,this.OnGamePlaying);
        EventManager.EventOn(EventType.CompleteStage,this,this.OnPlayerStageChange);
    }

    players:Runner[] = [];

    signup(runner:Runner)
    {
        this.players.push(runner);
    }

    OnGamePlaying()
    {
        Laya.timer.once(1000,this,()=>
        {
            Laya.timer.frameLoop(1,this,this.SortPlayer);
        })
        
    }

    OnGameEnd()
    {
        Laya.timer.clear(this,this.SortPlayer);
    }

    OnGameOver()
    {
        this.players = [];
        Laya.timer.clear(this,this.SortPlayer);
    }

    OnPlayerStageChange()
    {
        for(var i = 0;i < this.players.length;i++)
        {
            if(this.players[i].Ai)
            {
                if(this.players[i].die)
                {
                    this.players[i].Cheat();
                }
            }
        }
    }

    Champion:Runner;
    SortPlayer()
    {
        this.players.sort(this.Sort);
        EventManager.EventTrigger(EventType.PlayerRank,[this.players]);
        if(this.Champion == null || this.Champion.Id != this.players[0].Id)
        {
            this.Champion = this.players[0];
            EventManager.EventTrigger(EventType.crownchange,this.players[0].Id);
            EventManager.EventTrigger(EventType.ScoreChange,this.GetPlayerScore);
        }
    }

    get GetPlayerScore():number
    {
        for(var i = 0;i < this.players.length;i++)
        {
            var player = this.players[i];
            if(!player.Ai)
            {
                return i + 1;
            }
        }
    }

    Sort(a:Runner,b:Runner):number
    {
        if(a.m_sprite.transform.position.z > b.m_sprite.transform.position.z)
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
}