use crate::io;
use crate::mem::MaybeUninit;
use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use crate::os::fd::{AsRawFd, FromRawFd, RawFd};
use crate::sys::{cvt_io, io::FileDesc};
use crate::sys_common::{AsInner, IntoInner};
use crate::time::Duration;

use yggdrasil_rt::{
    net::{SocketOption, SocketType},
    sys as syscall,
};

#[derive(Debug)]
pub struct UdpSocket {
    fd: FileDesc,
    local: SocketAddr,
    remote: Option<SocketAddr>,
}

impl UdpSocket {
    pub fn bind(listen: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
        let listen = listen?;
        let raw = cvt_io(unsafe { syscall::bind_socket(listen, SocketType::UdpPacket) })?;
        let inner = unsafe { FileDesc::from_raw_fd(raw) };
        Ok(Self { fd: inner, local: *listen, remote: None })
    }

    pub fn connect(&self, _remote: io::Result<&SocketAddr>) -> io::Result<()> {
        todo!()
    }

    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        todo!()
    }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        todo!()
    }

    pub fn recv(&self, _buffer: &mut [u8]) -> io::Result<usize> {
        todo!()
    }

    pub fn recv_from(&self, buffer: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        let mut remote = MaybeUninit::uninit();
        let len =
            cvt_io(unsafe { syscall::receive_from(self.fd.as_raw_fd(), buffer, &mut remote) })?;
        Ok((len, unsafe { remote.assume_init() }))
    }

    pub fn send(&self, _buffer: &[u8]) -> io::Result<usize> {
        todo!()
    }

    pub fn send_to(&self, buffer: &[u8], dst: &SocketAddr) -> io::Result<usize> {
        let dst = Some(*dst);
        cvt_io(unsafe { syscall::send_to(self.fd.as_raw_fd(), buffer, &dst) })
    }

    pub fn peek(&self, _buf: &mut [u8]) -> io::Result<usize> {
        todo!()
    }

    pub fn peek_from(&self, _buffer: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        todo!()
    }

    pub fn duplicate(&self) -> io::Result<UdpSocket> {
        todo!()
    }

    pub fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        todo!()
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        todo!()
    }

    pub fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        todo!()
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        todo!()
    }

    pub fn set_ttl(&self, _ttl: u32) -> io::Result<()> {
        todo!()
    }

    pub fn ttl(&self) -> io::Result<u32> {
        todo!()
    }

    pub fn set_nonblocking(&self, _nonblocking: bool) -> io::Result<()> {
        todo!()
    }

    pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
        cvt_io(unsafe {
            syscall::set_socket_option(self.fd.as_raw_fd(), &SocketOption::Broadcast(broadcast))
        })
    }

    pub fn broadcast(&self) -> io::Result<bool> {
        let mut value = SocketOption::Broadcast(false);
        cvt_io(unsafe { syscall::get_socket_option(self.fd.as_raw_fd(), &mut value) })?;
        let SocketOption::Broadcast(value) = value else {
            unreachable!();
        };
        Ok(value)
    }

    pub fn set_multicast_loop_v4(&self, _loop_v4: bool) -> io::Result<()> {
        todo!()
    }

    pub fn multicast_loop_v4(&self) -> io::Result<bool> {
        todo!()
    }

    pub fn set_multicast_ttl_v4(&self, _ttl: u32) -> io::Result<()> {
        todo!()
    }

    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
        todo!()
    }

    pub fn set_multicast_loop_v6(&self, _loop_v6: bool) -> io::Result<()> {
        todo!()
    }

    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
        todo!()
    }

    pub fn join_multicast_v6(&self, _multiaddr: &Ipv6Addr, _interface: u32) -> io::Result<()> {
        todo!()
    }

    pub fn join_multicast_v4(
        &self,
        _multiaddr: &Ipv4Addr,
        _interface: &Ipv4Addr,
    ) -> io::Result<()> {
        todo!()
    }

    pub fn leave_multicast_v6(&self, _multiaddr: &Ipv6Addr, _interface: u32) -> io::Result<()> {
        todo!()
    }

    pub fn leave_multicast_v4(
        &self,
        _multiaddr: &Ipv4Addr,
        _interface: &Ipv4Addr,
    ) -> io::Result<()> {
        todo!()
    }

    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        todo!()
    }
}

impl IntoInner<FileDesc> for UdpSocket {
    fn into_inner(self) -> FileDesc {
        self.fd
    }
}

impl AsInner<FileDesc> for UdpSocket {
    fn as_inner(&self) -> &FileDesc {
        &self.fd
    }
}

impl AsRawFd for UdpSocket {
    fn as_raw_fd(&self) -> RawFd {
        self.fd.as_raw_fd()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for crate::net::UdpSocket {
    fn as_raw_fd(&self) -> RawFd {
        self.as_inner().as_raw_fd()
    }
}
