use std::collections::HashMap;

use data::tables::MainCityObjectID;
use proto::SceneUnitProtocolInfo;

use crate::logic::math::InteractScale;

use super::InteractComponent;

pub struct SceneUnit {
    pub tag: u32,
    pub interacts: HashMap<u32, InteractComponent>,
}

impl SceneUnit {
    pub fn new(template_id: MainCityObjectID) -> Self {
        let template = template_id.template();

        Self {
            tag: template.tag_id.value(),
            interacts: Self::create_default_interacts(
                &template.default_interact_ids,
                template.tag_id.value(),
                &template.interact_name,
                &template.interact_scale,
            ),
        }
    }

    pub fn protocol_info(&self) -> SceneUnitProtocolInfo {
        SceneUnitProtocolInfo {
            is_interactable: !self.interacts.is_empty(),
            npc_id: self.tag,
            interacts_info: self
                .interacts
                .iter()
                .map(|(id, comp)| (*id, comp.to_client()))
                .collect(),
            ..Default::default()
        }
    }

    fn create_default_interacts(
        interact_ids: &[u32],
        tag: u32,
        name: &str,
        scale: &str,
    ) -> HashMap<u32, InteractComponent> {
        let scale = InteractScale::from_str(scale).unwrap_or_default();

        interact_ids
            .iter()
            .map(|id| {
                (
                    *id,
                    InteractComponent {
                        participators: HashMap::from([(tag, name.to_string())]),
                        interact_id: tag,
                        scale: scale.clone(),
                    },
                )
            })
            .collect()
    }
}
