import GameObject from "./GameObject";
import Leg, { LegToward } from "./Leg";
import GameMgr from "../Mgr/GameMgr";
import { ControllerDirection } from "./PlayerController";
import DebugMgr from "../Mgr/DebugMgr";
import GameStage from "./GameStage";

export default class Legs {
    public get toward(): LegToward {
        return this.left.toward;
    }
    private left: Leg = null;
    private right: Leg = null;
    /**是否测量过步长 */
    private stepLength = null;

    private initPosX: number = null;

    constructor(gameStage: GameStage, rect: egret.Rectangle, texture: egret.Texture, toward: LegToward) {
        this.left = new Leg(gameStage, rect, texture, toward);
        gameStage.addChild(this.left);

        this.right = new Leg(gameStage, rect, texture, toward);
        gameStage.addChild(this.right);


        // return;
        //两腿交替行动
        this.left.act();
        this.left.onActed = () => {
            if (!this.stepLength) {
                this.stepLength = Math.abs(this.left.x - this.initPosX);
                this.right.land(this.initPosX + this.right.towardCoefficient * (this.stepLength / 2), -5);
            }

            this.right.act();
        }
        this.right.onActed = () => {
            this.left.act();
        }

        this.left.updateCallback = () => {
            if (this.toward == LegToward.Right) {
                if (this.posX > GameMgr.instance.stage.stageWidth + 600) {
                    this.left.destroy();
                    this.right.destroy();
                    console.error("destroy");
                }
            } else {
                if (this.posX < - 600) {
                    this.left.destroy();
                    this.right.destroy();
                    console.error("destroy");
                }
            }
            // DebugMgr.instance.updateLine(this.left.hashCode.toString() + "1", { startX: this.left.x, startY: 0, endX: this.left.x, endY: 750 });
            // DebugMgr.instance.updateLine(this.left.hashCode.toString() + "2", { startX: this.right.x, startY: 0, endX: this.right.x, endY: 750 });
            // DebugMgr.instance.updateLine(this.left.hashCode.toString() + "3", { startX: this.posX, startY: 0, endX: this.posX, endY: 750 }, { lineSize: 2, color: 0x0000ff });
        }
    }

    public setInitPosX(x: number) {
        this.initPosX = x;
        this.left.land(x, -2);
        this.right.land(x, -5);
    }
    public get posX() {
        if (this.toward == LegToward.Right) {
            return Math.min(this.right.x, this.left.x);
        } else {
            return Math.max(this.right.x, this.left.x);
        }
    }
}