use std::error::Error;

use common::{
    db::{self, SqlOpPlayerData},
    ServiceBox,
};

use crate::{config::DbgateConfig, network::NetworkMgr};

use super::LoginHandler;

pub struct DbgateService {
    pub config: DbgateConfig,
    pub network_mgr: NetworkMgr,
    pub service_box: ServiceBox,
    pub login_handler: LoginHandler,
    pub sql_op_player_data: SqlOpPlayerData,
}

impl DbgateService {
    pub async fn new(config: DbgateConfig) -> Result<Self, Box<dyn Error>> {
        let network_mgr = NetworkMgr::new(&config).await?;
        let service_box = ServiceBox::new(config.app_id, &config.applications);
        let db = db::connect(&config.database.connection_string).await?;
        let sql_op_player_data = SqlOpPlayerData::new(db);

        Ok(Self {
            config,
            network_mgr,
            service_box,
            login_handler: LoginHandler,
            sql_op_player_data,
        })
    }

    pub async fn run(&self) {
        self.network_mgr.run().await
    }
}
