use std::future::{Ready, ready};
use std::panic::AssertUnwindSafe;
use std::rc::Rc;

use actix_web::{
    Error,
    dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
};
use futures::FutureExt;
use futures::future::LocalBoxFuture;

use crate::status::api_err::ApiErr;

pub struct Catch;

impl<S, B> Transform<S, ServiceRequest> for Catch
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Transform = CatchMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(CatchMiddleware { service: Rc::new(service) }))
    }
}

pub struct CatchMiddleware<S> {
    service: Rc<S>,
}

impl<S, B> Service<ServiceRequest> for CatchMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let svc = self.service.clone();

        Box::pin(async move {
            let fut = svc.call(req);
            match AssertUnwindSafe(fut).catch_unwind().await {
                Ok(Ok(resp)) => Ok(resp),
                Ok(Err(e)) => Err(e),
                Err(_) => Err(Error::from(ApiErr::Panic)),
            }
        })
    }
}
