use std::{net::Ipv4Addr, sync::Arc};

use common::{
    net::{tools::Packet, NetError, ServiceType},
    ServiceQualifier,
};
use proto::{AddGateserverNotify, KeepAliveNotify, PacketHead};

use crate::gateserver_service;

pub struct DispatchConnect;

impl DispatchConnect {
    pub async fn on_connect(&self) -> Result<(), NetError> {
        let player_server_conf = &gateserver_service().config.net.player_server;

        gateserver_service()
            .service_box
            .push_packet_to_service(
                ServiceQualifier::Type(ServiceType::Dispatch),
                Packet::new(
                    AddGateserverNotify {
                        domain_name: String::new(),
                        outer_ip: u32::from_be_bytes(
                            player_server_conf
                                .outer_ip
                                .0
                                .parse::<Ipv4Addr>()
                                .unwrap()
                                .octets(),
                        ),
                        listen_port: player_server_conf.listen_port as u32,
                        use_domain_name: false,
                    },
                    PacketHead::default(),
                ),
            )
            .await
    }

    pub async fn keep_alive_loop(self: Arc<Self>) {
        loop {
            let _ = gateserver_service()
                .service_box
                .push_packet_to_service(
                    ServiceQualifier::Type(ServiceType::Dispatch),
                    Packet::new(
                        KeepAliveNotify::default(),
                        PacketHead {
                            sender_load: gateserver_service().get_service_load(),
                            ..Default::default()
                        },
                    ),
                )
                .await;
        }
    }
}
