// @input SceneObject collider
// @input Component.Camera cam
// @input SceneObject[] walls
// @input SceneObject playButton
// @input SceneObject ball
// @input Component.Text scoreText

var ballPhysics = script.ball.getComponent("Physics.BodyComponent");
var collider = script.collider.getTransform();
var touchPosition;
var zDepth = 80;
var isTouching = false;
var lerpedPosition;
var ballPosition;
var ballRotation;
var score = 0;

function onStart() {
    ballPosition = script.ball.getTransform().getLocalPosition();
    ballRotation = script.ball.getTransform().getLocalRotation();
    setupBoxPositions();
}
script.createEvent("OnStartEvent").bind(onStart);

function onUpdate() {
    updateColliderPositions();
}
script.createEvent("UpdateEvent").bind(onUpdate);

function onTouch(eventData) {
    isTouching = true;
    touchPosition = script.cam.screenSpaceToWorldSpace(eventData.getTouchPosition(), zDepth);
}
script.createEvent("TouchStartEvent").bind(onTouch);
script.createEvent("TouchMoveEvent").bind(onTouch);

function touchEnd() {
    isTouching = false;
}
script.createEvent("TouchEndEvent").bind(touchEnd);

function startGame() {
    script.ball.getTransform().setLocalPosition(ballPosition);
    script.ball.getTransform().setLocalRotation(ballRotation);
    ballPhysics.dynamic = false;
    script.collider.enabled = true;
    script.playButton.enabled = false;
    score = 0;
    script.scoreText.text = score.toString();
    
    var delayedEvent = script.createEvent("DelayedCallbackEvent");
    delayedEvent.bind(function(eventData) {
        ballPhysics.dynamic = true;
    });
    delayedEvent.reset(1);
    
    print("Game Started");
}
script.startGame = startGame;

function endGame() {
    script.scoreText.text = "";
    script.playButton.enabled = true;
    script.collider.enabled = false;
    print("Game Ended");
}

ballPhysics.onCollisionEnter.add(function(eventArgs) {
   var collision = eventArgs.collision;
    collision = collision.collider.getSceneObject().name;
    
    if (collision == "Ground") {
        endGame();
    } else if (collision == "Tube") {
        score++;
        script.scoreText.text = score.toString();
    }
});

function updateColliderPositions() {
    if (isTouching) {
        lerpedPosition = vec3.lerp(touchPosition, collider.getLocalPosition(), 0.5);
        collider.setLocalPosition(touchPosition);
    }
}

function setupBoxPositions() {
    var height = 2 * zDepth * Math.tan(script.cam.fov / 2);
    var width = height * script.cam.aspect;
    
    script.walls[0].getTransform().setLocalPosition(new vec3(0, -height / 2.5, -zDepth));
    script.walls[1].getTransform().setLocalPosition(new vec3(0, height * 3, -zDepth));
    script.walls[2].getTransform().setLocalPosition(new vec3(-width / 1.5, 0, -zDepth));
    script.walls[3].getTransform().setLocalPosition(new vec3(width / 1.5, 0, -zDepth));
}