

import {getTextureByName} from "./utils";
import {getStage} from "./utils";
import {LoopComponent} from "./LoopComponent";
import { props } from './../props';

export class Background extends engine.Container{
    partResHHL = ['hhl_after', 'hhl_front'];
    partResHB = ['hb_after','hb_front'];
    partResWH = ['wh_after','wh_front'];
    speeds = [];
    resArray=[];
    frameMovePos = 0;
    frameIndex;
    sumMovePos;
    _bgIndex;
    //需要的总帧数
    needFrameSum;
    initBg(){
        this.sumMovePos = 0;
        this.speeds.push(props.afterBGMoveSpeed);
        this.speeds.push(props.frontBGMoveSpeed);
        
        let bottomBg = new engine.Rect();
        bottomBg.x = 0;
        bottomBg.y = 0;
        bottomBg.width = getStage().width;
        bottomBg.height = 0;
        bottomBg.fillColor = 0x75c9f5;

        this.addChild(bottomBg);
        this.resArray.push(this.partResHHL)
        this.resArray.push(this.partResHB)
        this.resArray.push(this.partResWH)
        this._bgIndex = 0;
		const parts = [];
		for(let i = 0; i < 2; i++){
			let part = new LoopComponent();
			part.setupLoop([
				this.resArray[0][i],
				this.resArray[0][i],
			]);
			parts.push(part);
            this.addChild(part);
        }
       
        //(height - parts[1].height) / 2 - 200
        parts[1].y = 200;
    }
  
    setViewport(pos) {
        this.needFrameSum = (props.pierMoveTime/1000)*60;
        this.frameMovePos = pos/this.needFrameSum;
        this.frameIndex = 0;
        this.addEventListener(engine.Event.ENTER_FRAME,this.frameBack,this);
    }
    frameBack(){
        if( this.frameIndex < this.needFrameSum){
            for (let i = 0; i < 2; i++) {
                const part = <LoopComponent>this.getChildAt(i + 1);
                const speed = this.speeds[i];
                let tmpPos = ((this.frameMovePos * this.frameIndex) + this.sumMovePos ) * speed;
                part.setViewport(tmpPos)
            }
            this.frameIndex++
        }else{
            this.sumMovePos += this.frameMovePos * this.needFrameSum;
            this.frameIndex = 0
            this.removeEventListener(engine.Event.ENTER_FRAME,this.frameBack,this);
        }        
    }
    changeBg(index){
        for (let i = 0; i < 2; i++) {
            const part = <LoopComponent>this.getChildAt(i + 1);
            part.changeBg(this.resArray[index][i]);
            if(i == 1 && index ==1){
                part.y = 400;
            } 
            if(i == 1 && index ==2){
                part.y = 250;
            }   
        }
        this._bgIndex = index;
    }
    getBgIndex(){
        return this._bgIndex;
    }
}