use serde::{Deserialize, Serialize};

use super::dock::SplitFraction;
use super::geometry::LayoutPx;

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SplitterStep {
    Coarse,
    Fine,
}

impl SplitterStep {
    #[must_use]
    pub const fn fraction_step(self) -> f32 {
        match self {
            Self::Fine => 0.005,
            Self::Coarse => 0.05,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SplitterMove {
    DecreaseA(SplitterStep),
    IncreaseA(SplitterStep),
    Min,
    Max,
    Reset,
}

#[must_use]
pub fn apply_keyboard_move(
    current: SplitFraction,
    default: SplitFraction,
    mv: SplitterMove,
) -> SplitFraction {
    let next = match mv {
        SplitterMove::DecreaseA(step) => current.value() - step.fraction_step(),
        SplitterMove::IncreaseA(step) => current.value() + step.fraction_step(),
        SplitterMove::Min => 0.0,
        SplitterMove::Max => 1.0,
        SplitterMove::Reset => default.value(),
    };
    SplitFraction::clamped(next)
}

#[must_use]
pub fn fraction_from_drag(total: LayoutPx, handle: LayoutPx) -> SplitFraction {
    let total_v = total.value();
    if total_v <= 0.0 {
        return SplitFraction::HALF;
    }
    SplitFraction::clamped(handle.value() / total_v)
}
