use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use super::dock::SplitFraction;
use super::geometry::LayoutPx;
use crate::widget_id::WidgetId;

#[derive(Copy, Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct ScrollOffset {
    pub x: LayoutPx,
    pub y: LayoutPx,
}

impl ScrollOffset {
    pub const ZERO: Self = Self {
        x: LayoutPx::ZERO,
        y: LayoutPx::ZERO,
    };

    #[must_use]
    pub const fn new(x: LayoutPx, y: LayoutPx) -> Self {
        Self { x, y }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RetainedLayout {
    pub scroll: BTreeMap<WidgetId, ScrollOffset>,
    pub split: BTreeMap<WidgetId, SplitFraction>,
}

impl RetainedLayout {
    #[must_use]
    pub fn scroll_for(&self, id: WidgetId) -> ScrollOffset {
        self.scroll.get(&id).copied().unwrap_or(ScrollOffset::ZERO)
    }

    #[must_use]
    pub fn split_for(&self, id: WidgetId, default: SplitFraction) -> SplitFraction {
        self.split.get(&id).copied().unwrap_or(default)
    }

    pub fn set_scroll(&mut self, id: WidgetId, offset: ScrollOffset) {
        self.scroll.insert(id, offset);
    }

    pub fn set_split(&mut self, id: WidgetId, fraction: SplitFraction) {
        self.split.insert(id, fraction);
    }
}
