#pragma once

#include "core/script.hpp"
#include "utils/debug.hpp"

#include "constants.hpp"
#include "paddle_script.hpp"
#include "player_script.hpp"


struct game_script : frog::script
{
    void stable_update(frog::game_object&, frog::engine& engine) override
    {
        using namespace frog;

        engine.scenes->current().for_each_object(by_tag("ball"),
            [&](auto& ball)
        {
            if (distance(ball.model().pos, geo::vec3{ 0 }) > GroundSize)
            {
                ball_outside(ball, engine);
            }
        });
    }

    void ball_outside(frog::game_object& ball, frog::engine& engine)
    {
        ball.model().pos = { 0, Ball::Radius, 0 };

        engine.scenes->current()
            .for_each_script<player_script>(
                [&](auto& pl_script)
                {
                    pl_script.add_lives(-1);
                    if (pl_script.dead())
                    {
                        game_over(engine);
                    }
                });

        int count = 0;
        engine.scenes->current()
            .for_each_script<paddle_script>(frog::by_tag("paddle"),
                [&](const auto&) { count++; });

        int i = 0;
        engine.scenes->current()
            .for_each_script<paddle_script>(
                frog::by_tag("paddle"),
                [&](paddle_script& sc)
                {
                    sc.ball_magnet = i == 0;
                    i++;
                });
    }

    void game_over(frog::engine& engine)
    {
        engine.scenes->switch_scene("game_over");
    }
};
