//! MQTT5 Client/Server framework

pub mod client;
pub mod codec;
pub mod control;

mod default;
mod dispatcher;
mod handshake;
mod publish;
mod router;
mod server;
mod shared;
mod sink;

pub type Session<St> = crate::Session<MqttSink, St>;

use ntex_error::Error;
use std::num::NonZeroU16;

pub use self::control::{Control, ControlAck, CtlFlow, CtlFrame, CtlReason};
pub use self::handshake::{Handshake, HandshakeAck};
pub use self::publish::{Publish, PublishAck};
pub use self::router::Router;
pub use self::server::MqttServer;
pub use self::sink::{MqttSink, SubscribeBuilder, UnsubscribeBuilder};
pub use self::sink::{PublishBuilder, StreamingPayload};

pub use crate::topic::{TopicFilter, TopicFilterError};
pub use crate::{error, types::QoS};

const RECEIVE_MAX_DEFAULT: NonZeroU16 = NonZeroU16::new(65_535).unwrap();

fn disconnect(msg: &'static str) -> ControlAck {
    log::error!("{msg}");

    ControlAck {
        packet: control::Pkt::Disconnect(codec::Disconnect::new(
            codec::DisconnectReasonCode::ImplementationSpecificError,
        )),
        disconnect: true,
    }
}

pub trait ToPublishAck {
    type Error;

    fn try_ack(self) -> Result<PublishAck, Self::Error>;

    fn into_error(self) -> Self::Error;
}

impl<E: ToPublishAck + Clone> ToPublishAck for Error<E> {
    type Error = Error<E::Error>;

    fn try_ack(self) -> Result<PublishAck, Self::Error> {
        self.try_map(ToPublishAck::try_ack)
    }

    fn into_error(self) -> Self::Error {
        self.map(ToPublishAck::into_error)
    }
}

impl<E> ToPublishAck for E
where
    E: TryInto<PublishAck> + Into<E::Error>,
{
    type Error = E::Error;

    fn try_ack(self) -> Result<PublishAck, Self::Error> {
        self.try_into()
    }

    fn into_error(self) -> Self::Error {
        self.into()
    }
}
