//! Grand Theft Arena

use godot::classes::ISprite2D;
use godot::classes::Sprite2D;
use godot::prelude::*;

struct MyExtension;

#[gdextension]
unsafe impl ExtensionLibrary for MyExtension {}

#[derive(GodotClass)]
#[class(base=Sprite2D)]
struct Player {
    speed: f64,
    angular_speed: f64,

    base: Base<Sprite2D>,
}

#[godot_api]
impl ISprite2D for Player {
    fn init(base: Base<Sprite2D>) -> Self {
        Self {
            speed: 400.0,
            angular_speed: std::f64::consts::PI,
            base,
        }
    }

    fn physics_process(&mut self, delta: f64) {
        let input = Input::singleton();

        let speed = self.speed;
        let angular_speed = self.angular_speed;

        let mut base = self.base_mut();

        // Rotation
        if input.is_action_pressed("turn_left") {
            let radians = -angular_speed * delta;
            base.rotate(radians as f32);
        }
        if input.is_action_pressed("turn_right") {
            let radians = angular_speed * delta;
            base.rotate(radians as f32);
        }

        // Movement
        let mut velocity = Vector2::ZERO;
        if input.is_action_pressed("move_forward") {
            let forward = Vector2::UP.rotated(base.get_rotation());
            velocity += forward * speed as f32;
        }
        if input.is_action_pressed("move_backward") {
            let backward = Vector2::UP.rotated(base.get_rotation());
            velocity -= backward * speed as f32;
        }
        base.translate(velocity * delta as f32);
    }
}
