
import { MixBlend, MixDirection } from "./utils";
import { Slot } from "../Slot";
import { Attachment } from "../attachment/Attachment";
import { BaseTrack } from "./BaseTrack";
import { Spine } from "../Spine";

export interface IAttachmentAniData {
    name?: string,
    time: number,
    //需要替换的，根据name获取,到时上面的name不需要了
    // attachment: Attachment,
}
export class AttachmentAniTrack extends BaseTrack {
    resetValue() {
        this.slot.setToSetupPose()
    }
    constructor(
        /**
         * 需要改变附件的插槽
         */
        public slot: Slot,
        /**
         * 记录所有时间的数组，按顺序递增，没有的按最后一个时间的数据
         */
        public times: IAttachmentAniData[],
        /**
         * 初始，原始数据中获取的
         */
        // public originAttachment: Attachment
        private spine: Spine
    ) {
        super();
        this._instanceType = "AttachmentAniTrack";
        // 处理下默认数据
        times.forEach((t) => { t.time = t.time || 0 })
    }

    setValue(time: number, alpha: number = 1, blend: MixBlend = MixBlend.replace, direction: MixDirection = MixDirection.in) {
        var slot = this.slot;
        if (direction == MixDirection.out && blend == MixBlend.setup) {//还原成默认的。
            var attachmentName_1 = slot.data.attachment;
            slot.setAttachment(attachmentName_1 ? this.spine.getAttachment(this.spine.slots.indexOf(slot), attachmentName_1) : null);
            return;
        }
        var frames = this.times;
        if (time < frames[0].time) {
            if (blend == MixBlend.setup || blend == MixBlend.first || blend == MixBlend.replace) {//replace是后加的,待测试有没有问题
                var attachmentName_1 = slot.data.attachment;
                slot.setAttachment(attachmentName_1 ? this.spine.getAttachment(this.spine.slots.indexOf(slot), attachmentName_1) : null);
            }
            return;
        }
        var frameIndex = 0;
        if (time >= frames[frames.length - 1].time)
            frameIndex = frames.length - 1;
        else
            frameIndex = binarySearch(frames, time) - 1;
        var attachmentName = frames[frameIndex].name;
        slot.setAttachment(attachmentName == null ? null : this.spine.getAttachment(this.spine.slots.indexOf(slot), attachmentName));
    }
}


function binarySearch(values: IAttachmentAniData[], target: number) {
    var low = 0;
    var high = values.length - 2;
    if (high == 0) return 1;
    var current = high >>> 1;
    while (true) {
        if (values[current + 1].time <= target)
            low = current + 1;
        else
            high = current;
        if (low == high)
            return low + 1;
        current = (low + high) >>> 1;
    }
};