1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use async_trait::async_trait;

use crate::{Cache, CmpInOut, ComponentError};

pub struct Component<TConfig, TMsg> {
    cache: Option<Cache<TMsg>>,
    in_out: Option<CmpInOut<TMsg>>,
    config: Option<TConfig>,
}

impl<TConfig, TMsg> Component<TConfig, TMsg> {
    pub fn new(config: impl Into<TConfig>) -> Self {
        Self {
            cache: None,
            config: Some(config.into()),
            in_out: None,
        }
    }
}

#[async_trait]
impl<TConfig, TMsg> IComponent<TMsg> for Component<TConfig, TMsg>
where
    TMsg: Send + Sync,
    Self: IComponentProcess<TConfig, TMsg>,
    TConfig: Send,
{
    fn set_interface(&mut self, in_out: CmpInOut<TMsg>, cache: Cache<TMsg>) {
        self.cache = Some(cache);
        self.in_out = Some(in_out);
    }

    async fn spawn(&mut self) -> Result<(), ComponentError> {
        let config = self
            .config
            .take()
            .ok_or(ComponentError::Initialization("config not set".into()))?;

        let cache = self
            .cache
            .take()
            .ok_or(ComponentError::Initialization("cache not set".into()))?;

        let in_out = self
            .in_out
            .take()
            .ok_or(ComponentError::Initialization("in_out not set".into()))?;

        self.process(config, in_out, cache).await
    }
}

#[async_trait]
pub trait IComponentProcess<TConfig, TMsg> {
    async fn process(
        &self,
        config: TConfig,
        in_out: CmpInOut<TMsg>,
        cache: Cache<TMsg>,
    ) -> Result<(), ComponentError>;
}

#[async_trait]
pub trait IComponent<TMsg> {
    fn set_interface(&mut self, in_out: CmpInOut<TMsg>, cache: Cache<TMsg>);

    async fn spawn(&mut self) -> Result<(), ComponentError>;
}