use std::rc::{Rc, Weak};

use proto::PlayerLoginCompBin;
use tokio::sync::OnceCell;

use super::Player;

#[derive(Default)]
pub struct PlayerLoginComp {
    player: OnceCell<Weak<Player>>,
    pub taken_login_reward_config_list: Vec<u32>,
    pub last_login_refresh_time: u32,
    pub recv_questionnaire_mail_config_list: Vec<u32>,
    pub last_recv_questionnaire_mail_time: u32,
}

impl PlayerLoginComp {
    pub fn set_player(&self, player: Rc<Player>) {
        self.player.set(Rc::downgrade(&player)).unwrap();
    }

    #[allow(dead_code)]
    pub fn player(&self) -> Option<Rc<Player>> {
        self.player.get().map(|p| p.upgrade())?
    }

    pub fn init(&mut self) {}

    pub fn on_login(&mut self, is_new_player: bool) {
        self.refresh_login_reward(true);
        self.refresh_questionnaire_mail(is_new_player);
    }

    // TODO
    fn refresh_login_reward(&mut self, _is_login: bool) {}
    fn refresh_questionnaire_mail(&mut self, _is_new_player: bool) {}

    pub fn from_bin(bin: PlayerLoginCompBin) -> Self {
        Self {
            player: OnceCell::new(),
            taken_login_reward_config_list: bin.taken_login_reward_config_list,
            last_login_refresh_time: bin.last_login_refresh_time,
            recv_questionnaire_mail_config_list: bin.recv_questionnaire_mail_config_list,
            last_recv_questionnaire_mail_time: bin.last_recv_questionnaire_mail_time,
        }
    }

    pub fn to_bin(&self) -> PlayerLoginCompBin {
        PlayerLoginCompBin {
            taken_login_reward_config_list: self.taken_login_reward_config_list.clone(),
            last_login_refresh_time: self.last_login_refresh_time,
            recv_questionnaire_mail_config_list: self.recv_questionnaire_mail_config_list.clone(),
            last_recv_questionnaire_mail_time: self.last_recv_questionnaire_mail_time,
        }
    }
}
