/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2025 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use crate::{
    PacketC, PacketS, PlayerID,
    glam::{IVec2, Vec2},
};
use std::collections::HashSet;

const PLAYER_SIZE: f32 = 0.4;
const PLAYER_FRICTION: f32 = 15.0;
const PLAYER_SPEED: f32 = 55.0;
const BOOST_FACTOR: f32 = 2.5;
const BOOST_DURATION: f32 = 0.3;
const BOOST_RESTORE: f32 = 0.5;

pub struct MovementBase {
    pub input_direction: Vec2,
    pub input_boost: bool,
    pub position: Vec2,
    pub facing: Vec2,
    pub rotation: f32,
    pub velocity: Vec2,
    pub boosting: bool,
    pub stamina: f32,
}

impl MovementBase {
    pub fn new(position: Vec2) -> Self {
        Self {
            input_direction: Vec2::ZERO,
            input_boost: false,
            position,
            facing: Vec2::X,
            velocity: Vec2::ZERO,
            boosting: false,
            stamina: 0.,
            rotation: 0.,
        }
    }
    pub fn input(&mut self, direction: Vec2, boost: bool) {
        self.input_boost = boost;
        self.input_direction = direction;
    }
    pub fn update(&mut self, map: &HashSet<IVec2>, dt: f32) {
        let mut boost = self.input_boost;
        let mut direction = self.input_direction.clamp_length_max(1.);
        if direction.length() > 0.05 {
            self.facing = direction + (self.facing - direction) * (-dt * 10.).exp();
        }
        if direction.length() < 0.5 {
            direction *= 0.;
        }
        self.rotation = self.facing.x.atan2(self.facing.y);
        boost &= direction.length() > 0.1;
        self.boosting = boost && (self.boosting || self.stamina >= 1.) && self.stamina > 0.;
        self.stamina += if self.boosting {
            -dt / BOOST_DURATION
        } else {
            dt / BOOST_RESTORE
        };
        self.stamina = self.stamina.clamp(0., 1.);
        let speed = PLAYER_SPEED * if self.boosting { BOOST_FACTOR } else { 1. };
        self.velocity += direction * dt * speed;
        self.position += self.velocity * dt;
        self.velocity *= (-dt * PLAYER_FRICTION).exp();
        collide_player_tiles(self, map);
    }

    pub fn movement_packet_s(&self, player: PlayerID) -> PacketS {
        PacketS::Movement {
            pos: Some(self.position),
            boost: self.input_boost,
            dir: self.input_direction,
            player,
        }
    }
    pub fn movement_packet_c(&self, player: PlayerID) -> PacketC {
        PacketC::Movement {
            rot: self.rotation,
            pos: self.position,
            boost: self.input_boost,
            dir: self.input_direction,
            player,
        }
    }

    pub fn collide(&mut self, other: &mut Self, dt: f32) {
        let diff = self.position - other.position;
        let d = diff.length();
        if d < 0.01 {
            return;
        }
        if d > PLAYER_SIZE * 2. {
            return;
        }
        let norm = diff.normalize();
        let f = 100. / (1. + d);
        self.velocity += norm * f * dt
    }

    pub fn get_interact_target(&self) -> IVec2 {
        (self.position + Vec2::new(self.rotation.sin(), self.rotation.cos())).as_ivec2()
    }
}

fn collide_player_tiles(p: &mut MovementBase, map: &HashSet<IVec2>) {
    for xo in -1..=1 {
        for yo in -1..=1 {
            let tile = IVec2::new(xo, yo) + p.position.as_ivec2();
            if map.contains(&tile) {
                continue;
            }
            let tile = tile.as_vec2();
            let d = aabb_point_distance(tile, tile + Vec2::ONE, p.position);
            if d > PLAYER_SIZE {
                continue;
            }
            let h = 0.01;
            let d_sample_x =
                aabb_point_distance(tile, tile + Vec2::ONE, p.position + Vec2::new(h, 0.));
            let d_sample_y =
                aabb_point_distance(tile, tile + Vec2::ONE, p.position + Vec2::new(0., h));
            let grad = (Vec2::new(d_sample_x, d_sample_y) - d) / h;

            p.position += (PLAYER_SIZE - d) * grad;
            p.velocity -= grad * grad.dot(p.velocity);
        }
    }
}

pub fn aabb_point_distance(min: Vec2, max: Vec2, p: Vec2) -> f32 {
    (p - p.clamp(min, max)).length()
}
