#include "game.h"

#define DELAY 30000

Game::Game()
    :max_x(1000), max_y(800), direction(0), window(sf::VideoMode(max_x, max_y), "SFML Window"),
      racecar(300.0f, 30.0f, 1.7f) { // maxSpeed, acceleration, and steerSpeed values
    if (!font.loadFromFile("cascaydia.otf")) {
        std::cerr << "Failed to load font" << std::endl;
        exit(1);
    }
    
    // Create a text object for displaying speed
    speedText.setFont(font);

    racecar.setPosition(max_x / 2, max_y / 2); // Set initial position for the racecar
}

void Game::run() {
    sf::Clock clock;

    while (window.isOpen()) {
        float dt = clock.restart().asSeconds();

        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
            if (racecar.getSpeed() < 0) {
                racecar.brake(dt); // Apply brakes
            } else {
                racecar.accelerate(dt); // Reverse the car
            }
        } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
            if (racecar.getSpeed() > 0) {
                racecar.brake(dt); // Apply brakes
            } else {
                racecar.reverse(dt); // Reverse the car
            }
        } else {
            racecar.decelerate(dt); // No key pressed, decelerate as usual
        }


        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
            racecar.steer(dt, -1.0f); // Steer left
        } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
            racecar.steer(dt, 1.0f); // Steer right
        }

        racecar.update(dt);

        speedText.setString(std::to_string(static_cast<int>(racecar.getSpeed())) + " km/h");
        speedText.setCharacterSize(24);
        speedText.setFillColor(sf::Color::Green);
        speedText.setPosition(10, 770);
        if(racecar.getSpeed() < 0){
            speedText.setFillColor(sf::Color::Blue);
        }
        if(racecar.getSpeed() >= 150){
            speedText.setPosition(10, 767);
            speedText.setCharacterSize(27);
            speedText.setFillColor(sf::Color::Yellow);
        }
        if(racecar.getSpeed() >= 260){
            speedText.setPosition(10, 764);
            speedText.setCharacterSize(30);
            speedText.setFillColor(sf::Color::Red);
        }
            

        window.clear();
        window.draw(racecar.getDrawable()); // Draw the racecar
        window.draw(speedText);
        window.display();

        sf::sleep(sf::microseconds(DELAY));
    }
}

