use super::{ItemUID, ResourceItem, Weapon};
use data::tables::WeaponID;
use proto::{ItemModelBin, ItemSync};

pub struct ItemModel {
    uid_counter: u32,
    pub resources: Vec<ResourceItem>,
    pub weapons: Vec<Weapon>,
}

impl ItemModel {
    pub fn from_bin(bin: ItemModelBin) -> Self {
        Self {
            uid_counter: bin.item_uid_counter,
            resources: bin
                .resource_list
                .into_iter()
                .map(ResourceItem::from_bin)
                .collect(),
            weapons: bin.weapon_list.into_iter().map(Weapon::from_bin).collect(),
        }
    }

    pub fn to_bin(&self) -> ItemModelBin {
        ItemModelBin {
            item_uid_counter: self.uid_counter,
            resource_list: self.resources.iter().map(ResourceItem::to_bin).collect(),
            weapon_list: self.weapons.iter().map(Weapon::to_bin).collect(),
        }
    }

    pub fn add_resource(&mut self, template_id: u32, num: u32) {
        if let Some(item) = self
            .resources
            .iter_mut()
            .find(|item| item.template_id == template_id)
        {
            item.num += num as i32;
        } else {
            self.resources.push(ResourceItem {
                template_id,
                num: num as i32,
            });
        }
    }

    pub fn add_weapon(&mut self, template_id: WeaponID) -> ItemUID {
        let uid = self.next_uid();
        self.weapons.push(Weapon::new(template_id, uid));

        uid
    }

    pub fn item_sync(&self) -> ItemSync {
        ItemSync {
            resource_list: self.resources.iter().map(|i| i.to_client()).collect(),
            weapon_list: self.weapons.iter().map(|w| w.to_client()).collect(),
            ..Default::default()
        }
    }

    fn next_uid(&mut self) -> ItemUID {
        self.uid_counter += 1;
        self.uid_counter.into()
    }
}

impl Default for ItemModel {
    fn default() -> Self {
        Self {
            uid_counter: 0,
            resources: Vec::new(),
            weapons: Vec::new(),
        }
    }
}
