use std::{cell::RefCell, rc::Rc};

use crate::{Poll, Readiness, Token};

pub mod channel;
pub mod generic;
pub mod ping;
#[cfg(target_os = "linux")]
pub mod signals;
pub mod timer;

/// Trait representing an event source
///
/// This is the trait you need to implement if you wish to create your own
/// calloop-compatible event sources.
///
/// The 3 type parameter define the type of closure the user will need to
/// provide to process events for your event source.
///
/// The `process_events` method will be called when one of the FD you registered
/// is ready, with the associated readiness and token.
///
/// The last 3 methods are plumbing to let your source register itself with the
/// polling system. See their documentation for details.
pub trait EventSource {
    /// The type of events generated by your source.
    type Event;
    /// Some metadata of your event source
    ///
    /// This is typically useful if your source contains some internal state that
    /// the user may need to interact with when processing events. The user callback
    /// will receive a `&mut Metadata` reference.
    ///
    /// Just set to `()` if not needed.
    type Metadata;
    /// The return type of the user callback
    ///
    /// If the user needs to return some value back to your event source once its
    /// processing is finshed (to indicate success or failure for example), you can
    /// specify it using this type.
    ///
    /// Just set to `()` if not needed.
    type Ret;

    /// Process any relevant events
    ///
    /// This method will be called every time one of the FD you registered becomes
    /// ready, including the readiness details and the associated token.
    ///
    /// Your event source will then do some processing of the file descriptor(s) to generate
    /// events, and call the provided `callback` for each one of them.
    ///
    /// You should ensure you drained the file descriptors of their events, especially if using
    /// edge-triggered mode.
    fn process_events<F>(
        &mut self,
        readiness: Readiness,
        token: Token,
        callback: F,
    ) -> std::io::Result<()>
    where
        F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret;

    /// Register yourself to this poll instance
    ///
    /// You should register all your relevant file descriptors to the provided `Poll`
    /// using its `Poll::register` method.
    ///
    /// If you need to register more than one file descriptor, you can change the
    /// `sub_id` field of the `Token` to differentiate between them.
    fn register(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()>;

    /// Re-register your file descriptors
    ///
    /// Your should update the registration of all your relevant file descriptor to
    /// the provided `Poll` using its `Poll::reregister`, if necessary.
    fn reregister(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()>;

    /// Unregister your file descriptors
    ///
    /// You should unregister all your file descriptors from this `Poll` using its
    /// `Poll::unregister` method.
    fn unregister(&mut self, poll: &mut Poll) -> std::io::Result<()>;
}

pub(crate) struct Dispatcher<S, F> {
    source: S,
    callback: F,
}

impl<S, F> Dispatcher<S, F> {
    pub fn new(source: S, callback: F) -> Self {
        Dispatcher { source, callback }
    }
}

impl<Data, S, F> EventDispatcher<Data> for RefCell<Dispatcher<S, F>>
where
    S: EventSource + 'static,
    F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret,
{
    fn process_events(
        &self,
        readiness: Readiness,
        token: Token,
        data: &mut Data,
    ) -> std::io::Result<()> {
        let mut disp = self.borrow_mut();
        let Dispatcher {
            ref mut source,
            ref mut callback,
            ..
        } = *disp;
        source.process_events(readiness, token, |event, meta| callback(event, meta, data))
    }

    fn register(&self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
        self.borrow_mut().source.register(poll, token)
    }

    fn reregister(&self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
        self.borrow_mut().source.reregister(poll, token)
    }

    fn unregister(&self, poll: &mut Poll) -> std::io::Result<()> {
        self.borrow_mut().source.unregister(poll)
    }

    fn as_source_any(&self) -> std::cell::RefMut<dyn std::any::Any> {
        std::cell::RefMut::map(self.borrow_mut(), |disp| &mut disp.source)
    }

    fn into_source_any(self: Rc<Self>) -> Box<dyn std::any::Any> {
        let me = Rc::try_unwrap(self).unwrap_or_else(|_| panic!("Unwrapping a shared source."));
        Box::new(me.into_inner().source)
    }
}

pub(crate) trait EventDispatcher<Data> {
    fn process_events(
        &self,
        readiness: Readiness,
        token: Token,
        data: &mut Data,
    ) -> std::io::Result<()>;

    fn register(&self, poll: &mut Poll, token: Token) -> std::io::Result<()>;

    fn reregister(&self, poll: &mut Poll, token: Token) -> std::io::Result<()>;

    fn unregister(&self, poll: &mut Poll) -> std::io::Result<()>;

    fn as_source_any(&self) -> std::cell::RefMut<dyn std::any::Any>;

    fn into_source_any(self: Rc<Self>) -> Box<dyn std::any::Any>;
}

/// A token representing an event source inserted in the event loop
///
/// You'll need it to interact with your source via `LoopHandle`
pub struct Source<S: EventSource> {
    pub(crate) token: Token,
    pub(crate) _type: std::marker::PhantomData<*const S>,
}

/// An idle callback that was inserted in this loop
///
/// This handle allows you to cancel the callback. Dropping
/// it will *not* cancel it.
pub struct Idle {
    pub(crate) callback: Rc<RefCell<dyn CancellableIdle>>,
}

impl Idle {
    /// Cancel the idle callback if it was not already run
    pub fn cancel(self) {
        self.callback.borrow_mut().cancel();
    }
}

pub(crate) trait CancellableIdle {
    fn cancel(&mut self);
}

impl<F> CancellableIdle for Option<F> {
    fn cancel(&mut self) {
        self.take();
    }
}

pub(crate) trait IdleDispatcher<Data> {
    fn dispatch(&mut self, data: &mut Data);
}

impl<Data, F> IdleDispatcher<Data> for Option<F>
where
    F: FnMut(&mut Data),
{
    fn dispatch(&mut self, data: &mut Data) {
        if let Some(callabck) = self.as_mut() {
            callabck(data);
        }
    }
}
