import {getTextureByName} from "./utils";
export class LoopComponent extends engine.Container{
    parts: any[];

	onceInfo: any = {width: 0, height: 0, count: 0};
	loopInfo: any = {width: 0, height: 0, count: 0};

	constructor() {
		super();

		this.parts = [];
    }
    private setup(parts, info) {
        parts.forEach((item, index) => {
			let part;
			if(typeof item == 'string'){
				part = new engine.Sprite(getTextureByName(item));
			}else if(item instanceof engine.Texture){
				part = new engine.Sprite(item);
			}else {
				part = item;
			}
			this.addChild(part);
			this.parts.push(part);

			if (index == 0) {
				info.width = part.width;
				info.height = part.height;
			}
		});
		info.count = parts.length;

		this.setViewport(0, 0)
    }
    
	setupOnce(resArr) {
		this.setup(resArr, this.onceInfo);
	}

	setupLoop(resArr) {
		this.setup(resArr, this.loopInfo);
    }
    setViewport(x, y = 0) {
		const sizeField = y == 0 ? 'width' : 'height';
		const posField = y == 0 ? 'x' : 'y';
		const pos = y == 0 ? x : y;

		let index;
		const onceSize = this.onceInfo[sizeField];
		const onceCount = this.onceInfo.count;
		const loopCount = this.loopInfo.count;
		const loopSize = this.loopInfo[sizeField];
		index = onceSize == 0 ? -1 : Math.floor(pos / onceSize);

		if (index < 0 || index >= onceCount) {
			const loopIndex = Math.floor((pos - onceCount * onceSize) / this.loopInfo[sizeField]);
			index = onceCount + loopIndex;
		}

		let formerIndex = index < onceCount ? index : (index) % loopCount + onceCount;
		let latterIndex = index < onceCount ? index + 1 : (index - onceCount + 1) % loopCount + onceCount;
		let former = this.parts[formerIndex];
		let latter = this.parts[latterIndex];
		if(!former || !latter){
			console.log(formerIndex, latterIndex);
		}
		former[posField] = -(pos - loopSize * (index < onceCount ? index : index - onceCount) - (index < onceCount ? 0 : onceCount * onceSize));
		latter[posField] = former.x + (index < onceCount ? onceSize : loopSize);
	}
}