use std::{any::TypeId, ops::Deref, marker::PhantomData};
use anthill_di::{Constructor, DependencyContext, types::BuildDependencyResult};
use serde::Deserialize;
use crate::{contexts::RequestContext, results::CommandResult};
#[derive(Debug)]
pub struct DataTypeId(pub String);
impl Deref for DataTypeId {
    type Target = String;
    fn deref(&self) -> &Self::Target { &self.0 }
}
#[derive(Debug)]
pub struct MetaDataTypeId(pub String);
impl Deref for MetaDataTypeId {
    type Target = String;
    fn deref(&self) -> &Self::Target { &self.0 }
}
pub struct ButtonHandlerTypeId(pub TypeId);
impl Deref for ButtonHandlerTypeId {
    type Target = TypeId;
    fn deref(&self) -> &Self::Target { &self.0 }
}
#[async_trait_with_sync::async_trait]
pub trait IButtonHandler: Send + Sync {
    type TData: Sync + Send + for<'de> Deserialize<'de> + 'static;
    type TMetaData: Sync + Send + for<'de> Deserialize<'de> + 'static;
    async fn handle(&mut self, button_text: String, data: Self::TData, metadata: Self::TMetaData, request_context: RequestContext) -> CommandResult;
}
#[async_trait_with_sync::async_trait]
pub trait IButtonHandlerCallProducer: Send + Sync {
    async fn handle(&mut self, button_text: String, data: serde_json::Value, metadata: serde_json::Value, request_context: RequestContext) -> CommandResult;
}
#[async_trait_with_sync::async_trait]
impl<T: IButtonHandler + 'static> IButtonHandlerCallProducer for T
{
    async fn handle(&mut self, button_text: String, data: serde_json::Value, metadata: serde_json::Value, request_context: RequestContext) -> CommandResult {
        T::handle(self, button_text, serde_json::from_value::<T::TData>(data).unwrap(), serde_json::from_value::<T::TMetaData>(metadata).unwrap(), request_context).await
    }
}
pub trait IButtonHandlerMatchingRule: Sync + Send {
    fn get_data_type_id(&self) -> DataTypeId;
    fn get_metadata_type_id(&self) -> MetaDataTypeId;
    fn get_handler_type_id(&self) -> ButtonHandlerTypeId;
}
#[derive(Clone)]
pub struct ButtonHandlerMatchingRule<THandler: IButtonHandler + 'static> {
    pub handler_pd: PhantomData<THandler>,
}
#[async_trait_with_sync::async_trait(Sync)]
impl<THandler: IButtonHandler + 'static> Constructor for ButtonHandlerMatchingRule<THandler> {
    async fn ctor(_: DependencyContext) -> BuildDependencyResult<Self> {
        Ok(Self { handler_pd: Default::default() })
    }
}
impl<THandler: IButtonHandler + 'static> IButtonHandlerMatchingRule for ButtonHandlerMatchingRule<THandler>
{
    fn get_data_type_id(&self) -> DataTypeId { DataTypeId(std::any::type_name::<THandler::TData>().to_string()) }
    fn get_metadata_type_id(&self) -> MetaDataTypeId { MetaDataTypeId(std::any::type_name::<THandler::TMetaData>().to_string()) }
    fn get_handler_type_id(&self) -> ButtonHandlerTypeId { ButtonHandlerTypeId(TypeId::of::<THandler>()) }
}