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



export default class BaseBuffer implements IBuffer
{
    time: number;
    startTime: number;
    endTime: number;
    group: string;

    private static uuidIndex:number=0;
    private uuid:number;

    constructor(group:string,time:number){
        this.group=group;
        this.time=time;
        this.uuid=BaseBuffer.uuidIndex;
        BaseBuffer.uuidIndex++;
    }

    /**
     * 合并同组BUFFER 如果BUFFER必须是唯一则在Run 函数中调用。
     */
    protected mergeBuffer():void{
        let groupList:IBuffer[]=BufferManager.GetBufferGroup(this.group);
        let otherTime:number=0;
        let currentTime:number=director.getCurrentTime();
        let otherEndTime:number;
        if(groupList.length>1){
            groupList.forEach(element => {
                //排除自身
                if(element!=this){
                    otherEndTime=element.GetEndTime();
                    if(currentTime<otherEndTime){
                        otherTime+=otherEndTime-currentTime;
                    }
                }
            });
            //清理
            while(groupList.length>1){
                let buffer:IBuffer;
                for (let index = 0; index < groupList.length; index++) {
                    buffer = groupList[index];
                    //排除自身
                    if(buffer!=this){
                        BufferManager.RemoveBuffer(buffer);
                    }
                }
                groupList=BufferManager.GetBufferGroup(this.group);
            }
        }
        //合并时间
        this.time+=otherTime;
    }

    /**
     * 剩余时间
     */
    GetTimeRemaining(): number {
        let currentTime:number=director.getCurrentTime();
        let endTime:number=this.GetEndTime();
        if(currentTime<endTime){
            return endTime-currentTime;
        }
        return 0;
    }


    GetEndTime(): number {
        return this.endTime;
    }

    GetTime(): number {
        return this.time;
    }

    
    Tick(dt: number): void {
        
    }

    Run(data:any):void{
        this.startTime=director.getCurrentTime();
        this.endTime=this.startTime+this.time;
    }
    
    GetUUID(): number {
        return this.uuid;
    }
}