#include "game.hpp"

#include "state/commands.hpp"

#include "util.hpp"

#include <cmath>

#include "options.hpp"

Game::Game()
{
    // advance simulation in fixed steps with 100 Hz
    m_time_step          = 1.0 / 100.0;
    m_time_for_next_step = 0.0;

    m_state = new game::State();
    m_state->init();

    // XXX
    // one dummy ship for testing
    if (ISSET_FLAG(TEST_AUTORUN)) {
        m_state->addPlayer();
    }
}

bool Game::cycle(float dt)
{
    if (ISSET_FLAG(TEST_AUTORUN)) {
        // XXX the following is just testing code to do things

        static float total = 0.0;
        static float acc = 0.0;

        //if (total == 0.0) {
        //    float speed = 0.005;
        //    m_state->players[0]->addCommand(new game::SetSpeedCommand(speed));
        //    for (int i=0; i<100; i++) {
        //        float a = 2.0 * M_PI * util::randf_0_1();
        //        m_state->players[0]->addCommand(new game::ShootCommand(a));
        //    }
        //}

        acc   += dt;
        total += dt;

        float spawnInterval = 0.5;
        while (acc > spawnInterval) {
            acc -= spawnInterval;

            float angle = 360.0 * util::randf_0_1();
            float speed = 1.;

            m_state->players.back()->addCommand(new game::SetSpeedCommand(speed));
            m_state->players.back()->addCommand(new game::ShootCommand(angle));

            //static bool done = false;
            //if (total >= 10.0 && !done) {
            //    done = true;

            //    m_state->players[0]->addCommand(new game::ClearTracesCommand());
            //}
        }
    }

    // std::cout<<"adding dt: " << dt << std::endl;
    m_time_for_next_step += dt;

    int steps = 0;
    while (m_time_for_next_step >= m_time_step) {
        // std::cout<<"time now: " << m_time_for_next_step << std::endl;
        m_time_for_next_step -= m_time_step;

        m_state->advance(m_time_step);
        steps++;
    }

    // std::cout << m_time_for_next_step << " s remaining time, " << steps << "
    // steps taken." << std::endl;

    return true;
}
void Game::resize(int width, int height)
{
    m_state->setPlayingFieldSize(width, height);
}
