use data::tables::AvatarBaseID;

use crate::logic::game::LogicError;

use super::*;

pub async fn on_get_item_data(
    _session: &NetSession,
    player: &mut Player,
    _req: GetItemDataCsReq,
) -> NetResult<GetItemDataScRsp> {
    let item_model = &player.item_model;

    Ok(GetItemDataScRsp {
        retcode: Retcode::RetSucc.into(),
        resource_list: item_model.resources.iter().map(|i| i.to_client()).collect(),
        weapon_list: item_model.weapons.iter().map(|w| w.to_client()).collect(),
        ..Default::default()
    })
}

pub async fn on_weapon_dress(
    session: &NetSession,
    player: &mut Player,
    req: WeaponDressCsReq,
) -> NetResult<WeaponDressScRsp> {
    player.dress_weapon(
        AvatarBaseID::new(req.avatar_id).map_err(LogicError::from)?,
        req.weapon_uid.into(),
    )?;

    session
        .notify(PlayerSyncScNotify {
            avatar: Some(player.role_model.avatar_sync()),
            item_sync: Some(player.item_model.item_sync()),
            ..Default::default()
        })
        .await?;

    Ok(WeaponDressScRsp {
        retcode: Retcode::RetSucc.into(),
    })
}

pub async fn on_weapon_un_dress(
    session: &NetSession,
    player: &mut Player,
    req: WeaponUnDressCsReq,
) -> NetResult<WeaponUnDressScRsp> {
    let avatar_id = AvatarBaseID::new(req.avatar_id).map_err(LogicError::from)?;
    let avatar = player
        .role_model
        .avatar_list
        .iter_mut()
        .find(|a| a.template_id == avatar_id)
        .ok_or(Retcode::RetFail)?;

    avatar.weapon_uid = None;

    session
        .notify(PlayerSyncScNotify {
            avatar: Some(player.role_model.avatar_sync()),
            ..Default::default()
        })
        .await?;

    Ok(WeaponUnDressScRsp {
        retcode: Retcode::RetSucc.into(),
    })
}
