use godot::classes::{AnimatedSprite2D, Area2D, IArea2D, Input};
use godot::prelude::*;

#[derive(GodotClass)]
#[class(base=Area2D)]
struct Player {
  #[export]
  speed: f32,
  screen_size: Rect2,

  // required
  base: Base<Area2D>,
}

#[godot_api]
impl IArea2D for Player {
  fn init(base: Base<Area2D>) -> Self {
    Self {
      speed: 400.0,
      screen_size: Rect2::default(),

      base,
    }
  }

  fn ready(&mut self) {
    self.screen_size = self.base().get_viewport_rect();
  }

  fn process(&mut self, delta: f32) {
    let input = Input::singleton();
    let mut animated_sprite_2d = self.base().get_node_as::<AnimatedSprite2D>("AnimatedSprite2D");

    let mut velocity = Vector2::default();

    if input.is_action_pressed("move_right") {
      velocity.x += 1.0;
    }
    if input.is_action_pressed("move_left") {
      velocity.x -= 1.0;
    }
    if input.is_action_pressed("move_down") {
      velocity.y += 1.0;
    }
    if input.is_action_pressed("move_up") {
      velocity.y -= 1.0;
    }

    if velocity.length() > 0.0 {
      velocity = velocity.normalized() * self.speed;
      animated_sprite_2d.play();
    } else {
      animated_sprite_2d.stop();
    }

    let mut position = self.base().get_position();
    position = (position + (velocity * delta)).clamp(Vector2::ZERO, self.screen_size.size);

    self.base_mut().set_position(position);
  }
}
