use serde::{Deserialize, Serialize};
use specs::{
    error::NoError,
    saveload::{ConvertSaveload, Marker},
    Component, Entity, HashMapStorage, VecStorage,
};

use crate::misc::FlaggedStorage;

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Fleet {
    pub orbit_min: f32,
    pub orbit_max: f32,
}

#[derive(Copy, Clone, Debug)]
pub struct Owned {
    pub owner: Entity,
}

#[derive(Serialize, Deserialize)]
pub struct OwnedData<M> {
    pub owner: M,
}

impl Component for Fleet {
    type Storage = HashMapStorage<Self>;
}

impl Component for Owned {
    type Storage = FlaggedStorage<Self, VecStorage<Self>>;
}

impl<M> ConvertSaveload<M> for Owned
where
    for<'de> M: Marker + Serialize + Deserialize<'de>,
{
    type Data = OwnedData<M>;
    type Error = NoError;

    fn convert_into<F>(&self, mut ids: F) -> Result<Self::Data, Self::Error>
    where
        F: FnMut(Entity) -> Option<M>,
    {
        let owner = ids(self.owner).unwrap();

        Ok(OwnedData { owner })
    }

    fn convert_from<F>(data: Self::Data, mut ids: F) -> Result<Self, Self::Error>
    where
        F: FnMut(M) -> Option<Entity>,
    {
        let owner = ids(data.owner).unwrap();

        Ok(Owned { owner })
    }
}
