import { director } from "cc";
import IBuffer from "./IBuffer";



export default class BufferManager
{
    private static __groupBufferMap:Map<string,IBuffer[]>=new Map<string,IBuffer[]>();
    private static __bufferMap:Map<number,IBuffer>=new Map<number,IBuffer>();


    /**
     * 运行BUFFER
     * @param value 
     * @param data 
     */
    public static RunBuffer(value:IBuffer,data?:any):void{
        if(this.AddBuffer(value)){
            value.Run(data);
        }
    }

    /**
     * 添加BUFFER
     * @param value 
     */
    public static AddBuffer(value:IBuffer):boolean{
        let group:IBuffer[];
        if(this.__groupBufferMap.has(value.group)){
            group=this.__groupBufferMap.get(value.group);
            if(group.indexOf(value)>=0){
                return false;
            }
        }else{
            group=[];
            this.__groupBufferMap.set(value.group,group);
        }
        group.push(value);
        this.__bufferMap.set(value.GetUUID(),value);
        return true;
    }

    /**
     * 删除buffer
     * @param value 
     */
    public static RemoveBuffer(value:IBuffer):void{
        if(this.__bufferMap.has(value.GetUUID())==false){
            return;
        }
        this.__bufferMap.delete(value.GetUUID());
        let group:IBuffer[]=this.__groupBufferMap.get(value.group);
        let index:number=group.indexOf(value);
        group.splice(index,1);
    }

    /**
     * 获取BUFFER 组
     * @param group 
     */
    public static GetBufferGroup(group:string):IBuffer[]{
        if(this.__groupBufferMap.has(group)==false){
            return null;
        }
        return this.__groupBufferMap.get(group);
    }

    /**
     * 通过BUFFER 唯一ID 获取BUFFER
     * @param uuid 
     */
    public static GetBuffer(uuid:number):IBuffer{
        if(this.__bufferMap.has(uuid)==false){
            return null;
        }
        return this.__bufferMap.get(uuid);
    }
    /**
     * 心跳
     * @param dt 
     */
    public static Tick(dt:number):void{
        let currentTime:number=director.getCurrentTime();
        let removeList:IBuffer[]=[];
        this.__bufferMap.forEach((value , key) =>{
           value.Tick(dt);
           if(currentTime>value.GetEndTime()){
                removeList.push(value);
           }
        });
        //删除超过时间的BUFFER
        removeList.forEach(element => {
            this.RemoveBuffer(element);
        });
    }
}