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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//!
//! Cli trait for implementing a user-side command-line processor.
//!

use crate::error::Error;
use crate::parse;
pub use crate::result::Result;
use crate::terminal::Terminal;
use async_trait::async_trait;
use downcast::{downcast_sync, AnySync};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex, MutexGuard},
};
pub use workflow_terminal_macros::{declare_handler, register_handlers, Handler};

#[async_trait]
pub trait Cli: Sync + Send {
    fn init(self: Arc<Self>, _term: &Arc<Terminal>) -> Result<()> {
        Ok(())
    }
    async fn digest(self: Arc<Self>, term: Arc<Terminal>, cmd: String) -> Result<()>;
    async fn complete(
        self: Arc<Self>,
        term: Arc<Terminal>,
        cmd: String,
    ) -> Result<Option<Vec<String>>>;
    fn prompt(&self) -> Option<String>;
}

pub trait Context: Sync + Send + AnySync {
    fn term(&self) -> Arc<Terminal>;
}
downcast_sync!(dyn Context);
downcast_sync!(dyn Context + Sync + Send);

impl From<&dyn Context> for Arc<Terminal> {
    fn from(ctx: &dyn Context) -> Arc<Terminal> {
        ctx.term()
    }
}

#[async_trait]
pub trait Handler: Sync + Send + AnySync {
    fn verb(&self, _ctx: &Arc<dyn Context>) -> Option<&'static str> {
        None
    }
    fn condition(&self, ctx: &Arc<dyn Context>) -> bool {
        self.verb(ctx).is_some()
    }
    fn help(&self, _ctx: &Arc<dyn Context>) -> &'static str {
        ""
    }
    fn dyn_help(&self, _ctx: &Arc<dyn Context>) -> String {
        "".to_owned()
    }
    async fn complete(&self, _ctx: &Arc<dyn Context>, _cmd: &str) -> Result<Option<Vec<String>>> {
        Ok(None)
    }
    async fn start(self: Arc<Self>, _ctx: &Arc<dyn Context>) -> Result<()> {
        Ok(())
    }
    async fn stop(self: Arc<Self>, _ctx: &Arc<dyn Context>) -> Result<()> {
        Ok(())
    }
    async fn handle(
        self: Arc<Self>,
        ctx: &Arc<dyn Context>,
        argv: Vec<String>,
        cmd: &str,
    ) -> Result<()>;
}

downcast_sync!(dyn Handler);

pub fn get_handler_help(handler: Arc<dyn Handler>, ctx: &Arc<dyn Context>) -> String {
    let s = handler.help(ctx);
    if s.is_empty() {
        handler.dyn_help(ctx)
    } else {
        s.to_string()
    }
}

#[derive(Default)]
struct Inner {
    handlers: HashMap<String, Arc<dyn Handler>>,
}

#[derive(Default)]
pub struct HandlerCli {
    inner: Arc<Mutex<Inner>>,
}

impl HandlerCli {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(Inner::default())),
        }
    }

    fn inner(&self) -> MutexGuard<Inner> {
        self.inner.lock().unwrap()
    }

    pub fn collect(&self) -> Vec<Arc<dyn Handler>> {
        self.inner().handlers.values().cloned().collect::<Vec<_>>()
    }

    pub fn get(&self, name: &str) -> Option<Arc<dyn Handler>> {
        self.inner().handlers.get(name).cloned()
    }

    pub fn register<T, H>(&self, ctx: &Arc<T>, handler: H)
    where
        T: Context + Sized,
        H: Handler + Send + Sync + 'static,
    {
        let ctx: Arc<dyn Context> = ctx.clone();
        match handler.verb(&ctx) {
            Some(name) if handler.condition(&ctx) => {
                self.inner()
                    .handlers
                    .insert(name.to_lowercase(), Arc::new(handler));
            }
            _ => {}
        }
    }

    pub fn register_arc<T, H>(&self, ctx: &Arc<T>, handler: &Arc<H>)
    where
        T: Context + Sized,
        H: Handler + Send + Sync + 'static,
    {
        let ctx: Arc<dyn Context> = ctx.clone();
        match handler.verb(&ctx) {
            Some(name) if handler.condition(&ctx) => {
                self.inner()
                    .handlers
                    .insert(name.to_lowercase(), handler.clone());
            }
            _ => {}
        }
    }

    pub fn unregister(&self, name: &str) -> Option<Arc<dyn Handler>> {
        self.inner().handlers.remove(name)
    }

    pub fn clear(&self) -> Result<()> {
        self.inner().handlers.clear();
        Ok(())
    }

    pub async fn start<T>(&self, ctx: &Arc<T>) -> Result<()>
    where
        T: Context + Sized,
    {
        let ctx: Arc<dyn Context> = ctx.clone();
        let handlers = self.collect();
        for handler in handlers.iter() {
            handler.clone().start(&ctx).await?;
        }
        Ok(())
    }

    pub async fn stop<T>(&self, ctx: &Arc<T>) -> Result<()>
    where
        T: Context + Sized,
    {
        let handlers = self.collect();
        let ctx: Arc<dyn Context> = ctx.clone();
        for handler in handlers.into_iter() {
            handler.clone().start(&ctx).await?;
        }
        Ok(())
    }

    pub async fn execute<T>(&self, ctx: &Arc<T>, cmd: &str) -> Result<()>
    where
        T: Context + Sized,
    {
        let ctx: Arc<dyn Context> = ctx.clone();

        let argv = parse(cmd);
        let action = argv[0].to_lowercase();

        let handler = self.get(action.as_str());
        if let Some(handler) = handler {
            handler
                .clone()
                .handle(&ctx, argv[1..].to_vec(), cmd)
                .await?;
            Ok(())
        } else {
            Err(Error::CommandNotFound(action))
        }
    }

    pub async fn complete<T>(&self, ctx: &Arc<T>, cmd: &str) -> Result<Option<Vec<String>>>
    where
        T: Context + Sized,
    {
        let ctx: Arc<dyn Context> = ctx.clone();

        let argv = parse(cmd);
        let action = argv[0].to_lowercase();

        let handler = self.get(action.as_str());
        if let Some(handler) = handler {
            Ok(handler.clone().complete(&ctx, cmd).await?)
        } else {
            Err(Error::CommandNotFound(action))
        }
    }
}