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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
pub mod block;
pub mod cmd;
pub mod error;
pub mod format;
pub mod store;
pub mod style;
pub mod wrapper;

pub use error::Error;
pub use error::Result;

pub mod prelude {
    pub use crate::block::Block;
    pub use crate::cmd::AddStore2Block;
    pub use crate::cmd::BlockMut;
    pub use crate::cmd::Command;
    pub use crate::format::DefaultAppPolicy;
    pub use crate::format::DefaultPolicy;
    pub use crate::format::HelpDisplay;
    pub use crate::format::HelpPolicy;
    pub use crate::store::Store;
    pub use crate::style::Align;
    pub use crate::style::Style;
    pub use crate::AppHelp;
}

use crate::block::Block;
use crate::cmd::Command;
use crate::format::DefaultAppPolicy;
use crate::format::DefaultPolicy;
use crate::format::HelpPolicy;
use crate::store::Store;
use crate::style::Style;

use std::io::Stdout;
use std::{borrow::Cow, io::Write};

#[derive(Debug, Clone)]
pub struct AppHelp<'a, W> {
    style: Style,

    writer: W,

    blocks: Vec<Block<'a, Cow<'a, str>>>, // store command sections

    cmds: Vec<Command<'a>>,

    global: usize,

    wrap_max_width: usize,

    usage_new_line: usize,
}

impl<'a> Default for AppHelp<'a, Stdout> {
    fn default() -> Self {
        Self {
            style: Default::default(),
            writer: std::io::stdout(),
            blocks: Default::default(),
            cmds: Default::default(),
            global: 0,
            wrap_max_width: 0,
            usage_new_line: 0,
        }
    }
}

impl<'a, W: Write> AppHelp<'a, W> {
    pub fn new<S: Into<Cow<'a, str>>>(
        name: S,
        head: S,
        foot: S,
        style: Style,
        writer: W,
        max_width: usize,
        usage_new_line: usize,
    ) -> Self {
        Self {
            writer,
            style,
            blocks: vec![],
            cmds: vec![],
            global: 0,
            wrap_max_width: max_width,
            usage_new_line,
        }
        .with_global(name, head, foot)
    }

    pub fn with_global<S: Into<Cow<'a, str>>>(mut self, name: S, head: S, foot: S) -> Self {
        let name = name.into();
        let hint = Cow::from("");
        let help = Cow::from("");
        let head = head.into();
        let foot = foot.into();
        let global = Command::new(name, hint, help, head, foot);

        self.cmds.push(global);
        self.global = self.cmds.len() - 1;
        self
    }

    pub fn foot(&self) -> Cow<'a, str> {
        self.global().foot()
    }

    pub fn head(&self) -> Cow<'a, str> {
        self.global().head()
    }

    pub fn name(&self) -> Cow<'a, str> {
        self.global().name()
    }

    pub fn style(&self) -> &Style {
        &self.style
    }

    pub fn wrap_max_width(&self) -> usize {
        self.wrap_max_width
    }

    pub fn usage_new_line(&self) -> usize {
        self.usage_new_line
    }

    pub fn global(&self) -> &Command<'a> {
        &self.cmds[self.global]
    }

    pub fn global_mut(&mut self) -> &mut Command<'a> {
        &mut self.cmds[self.global]
    }

    pub fn block(&self) -> &[Block<'a, Cow<'a, str>>] {
        &self.blocks
    }

    pub fn block_mut(&mut self) -> &mut [Block<'a, Cow<'a, str>>] {
        &mut self.blocks
    }

    /// If the app has command except global one.
    pub fn has_cmd(&self) -> bool {
        self.cmds.len() >= 2
    }

    /// If the app has position args in any command.
    pub fn has_pos(&self) -> bool {
        self.cmds.iter().any(|cmd| cmd.has_position())
    }

    pub fn find_cmd<S: Into<Cow<'a, str>>>(&self, cmd: S) -> Option<&Command<'a>> {
        let name = cmd.into();

        self.cmds.iter().find(|v| v.name() == name)
    }

    pub fn find_cmd_mut<S: Into<Cow<'a, str>>>(&mut self, cmd: S) -> Option<&mut Command<'a>> {
        let name = cmd.into();

        self.cmds.iter_mut().find(|v| v.name() == name)
    }

    pub fn find_block<S: Into<Cow<'a, str>>>(&self, block: S) -> Option<&Block<'a, Cow<'a, str>>> {
        let name = block.into();

        self.blocks.iter().find(|v| v.name() == name)
    }

    pub fn find_block_mut<S: Into<Cow<'a, str>>>(
        &mut self,
        block: S,
    ) -> Option<&mut Block<'a, Cow<'a, str>>> {
        let name = block.into();

        self.blocks.iter_mut().find(|v| v.name() == name)
    }

    pub fn with_name<S: Into<Cow<'a, str>>>(mut self, name: S) -> Self {
        self.global_mut().set_name(name);
        self
    }

    pub fn with_head<S: Into<Cow<'a, str>>>(mut self, head: S) -> Self {
        self.global_mut().set_head(head);
        self
    }

    pub fn with_foot<S: Into<Cow<'a, str>>>(mut self, foot: S) -> Self {
        self.global_mut().set_foot(foot);
        self
    }

    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn with_writer(mut self, writer: W) -> Self {
        self.writer = writer;
        self
    }

    pub fn set_name<S: Into<Cow<'a, str>>>(&mut self, name: S) -> &mut Self {
        self.global_mut().set_name(name);
        self
    }

    pub fn set_head<S: Into<Cow<'a, str>>>(&mut self, head: S) -> &mut Self {
        self.global_mut().set_head(head);
        self
    }

    pub fn set_foot<S: Into<Cow<'a, str>>>(&mut self, foot: S) -> &mut Self {
        self.global_mut().set_foot(foot);
        self
    }

    pub fn set_style(&mut self, style: Style) -> &mut Self {
        self.style = style;
        self
    }

    pub fn set_write(&mut self, writer: W) -> &mut Self {
        self.writer = writer;
        self
    }

    pub fn add_block(&mut self, block: Block<'a, Cow<'a, str>>) -> Result<&mut Self> {
        if self.find_block(block.name()).is_some() {
            Err(Error::DuplicatedBlockName(block.name().to_string()))
        } else {
            self.blocks.push(block);
            Ok(self)
        }
    }

    pub fn add_cmd<S: Into<Cow<'a, str>>>(
        &mut self,
        block: S,
        cmd: Command<'a>,
    ) -> Result<&mut Self> {
        let block = block.into();

        self.find_block_mut(block.clone())
            .ok_or_else(|| Error::InvalidBlockName(block.to_string()))?
            .push(cmd.name());
        if self.find_cmd(cmd.name()).is_some() {
            Err(Error::DuplicatedCommandName(cmd.name().to_string()))
        } else {
            self.cmds.push(cmd);
            Ok(self)
        }
    }

    pub fn new_block<S: Into<Cow<'a, str>>>(&mut self, name: S) -> Result<AddBlock2App<'a, '_>> {
        let name = name.into();

        if self.find_block(name.clone()).is_some() {
            Err(Error::DuplicatedBlockName(name.to_string()))
        } else {
            Ok(AddBlock2App::new(&mut self.blocks, name))
        }
    }

    pub fn new_cmd<S: Into<Cow<'a, str>>>(
        &mut self,
        block: S,
        name: S,
    ) -> Result<AddCmd2App<'a, '_, W>> {
        let name = name.into();
        let block = block.into();

        self.find_block_mut(block.clone())
            .ok_or_else(|| Error::InvalidBlockName(block.to_string()))?;
        if self.find_cmd(name.clone()).is_some() {
            Err(Error::DuplicatedCommandName(name.to_string()))
        } else {
            Ok(AddCmd2App::new(self, block, name))
        }
    }

    pub fn display(&mut self, show_global: bool) -> Result<()> {
        let policy = DefaultAppPolicy::new(
            vec![],
            self.wrap_max_width,
            show_global,
            self.usage_new_line,
        );
        let help = policy.format(self).ok_or_else(|| {
            Error::raise("Can not format app help with DefaultAppPolicy".to_string())
        })?;

        writeln!(&mut self.writer, "{}", help)
            .map_err(|e| Error::raise(format!("Can not write to handler: {:?}", e)))
    }

    pub fn display_with<P>(&mut self, policy: P) -> Result<()>
    where
        P: HelpPolicy<'a, Self>,
    {
        let help = policy
            .format(self)
            .ok_or_else(|| Error::raise("Can not format app help with given policy".to_string()))?;

        writeln!(&mut self.writer, "{}", help)
            .map_err(|e| Error::raise(format!("Can not write to handler: {:?}", e)))
    }

    pub fn display_cmd<S>(&mut self, cmd: S) -> Result<()>
    where
        S: Into<Cow<'a, str>>,
    {
        let name = cmd.into();
        let cmd = self
            .cmds
            .iter()
            .find(|v| v.name() == name)
            .ok_or_else(|| Error::raise(format!("Can not find cmd {name}")))?;
        let policy = DefaultPolicy::new(
            self.name(),
            self.style.clone(),
            vec![],
            self.wrap_max_width,
            true,
            self.usage_new_line,
        );
        let help = policy
            .format(cmd)
            .ok_or_else(|| Error::raise("Can not format cmd help with given policy".to_string()))?;

        writeln!(&mut self.writer, "{}", help)
            .map_err(|e| Error::raise(format!("Can not write to handler: {:?}", e)))
    }

    pub fn display_cmd_with<S, P>(&mut self, cmd: S, policy: P) -> Result<()>
    where
        P: HelpPolicy<'a, Command<'a>>,
        S: Into<Cow<'a, str>>,
    {
        let name = cmd.into();
        let cmd = self
            .cmds
            .iter()
            .find(|v| v.name() == name)
            .ok_or_else(|| Error::raise(format!("Can not find cmd {name}")))?;
        let help = policy.format(cmd).ok_or_else(|| {
            Error::raise(format!("Can not format help of {name} with given policy"))
        })?;

        writeln!(&mut self.writer, "{}", help)
            .map_err(|e| Error::raise(format!("Can not write to handler: {:?}", e)))
    }
}

pub struct AddStore2App<'a, 'b> {
    store: Store<'a>,

    block: &'b mut Block<'a, Store<'a>>,

    added: bool,
}

impl<'a, 'b> AddStore2App<'a, 'b> {
    pub fn new<S: Into<Cow<'a, str>>>(block: &'b mut Block<'a, Store<'a>>, name: S) -> Self {
        let mut store = Store::default();

        store.set_optional(true);
        store.set_name(name);
        Self {
            block,
            store,
            added: false,
        }
    }

    pub fn set_optional(mut self, optional: bool) -> Self {
        self.store.set_optional(optional);
        self
    }

    pub fn set_position(mut self, position: bool) -> Self {
        self.store.set_position(position);
        self
    }

    pub fn set_hint<S: Into<Cow<'a, str>>>(mut self, hint: S) -> Self {
        self.store.set_hint(hint);
        self
    }

    pub fn set_help<S: Into<Cow<'a, str>>>(mut self, help: S) -> Self {
        self.store.set_help(help);
        self
    }

    pub fn set_name<S: Into<Cow<'a, str>>>(mut self, name: S) -> Self {
        self.store.set_name(name);
        self
    }

    pub fn set_type<S: Into<Cow<'a, str>>>(mut self, type_name: S) -> Self {
        self.store.set_type(type_name);
        self
    }

    pub fn submit(mut self) {
        if !self.added {
            let store = std::mem::take(&mut self.store);

            self.block.attach(store);
            self.added = true;
        }
    }
}

impl<'a, 'b> Drop for AddStore2App<'a, 'b> {
    fn drop(&mut self) {
        if !self.added {
            let store = std::mem::take(&mut self.store);

            self.block.attach(store);
            self.added = true;
        }
    }
}

pub struct AddBlock2App<'a, 'b> {
    block: Block<'a, Cow<'a, str>>,

    blocks: &'b mut Vec<Block<'a, Cow<'a, str>>>,

    added: bool,
}

impl<'a, 'b> AddBlock2App<'a, 'b> {
    pub fn new<S: Into<Cow<'a, str>>>(
        blocks: &'b mut Vec<Block<'a, Cow<'a, str>>>,
        name: S,
    ) -> Self {
        let mut block = Block::default();

        block.set_name(name);
        Self {
            blocks,
            block,
            added: false,
        }
    }

    pub fn attach<S: Into<Cow<'a, str>>>(&mut self, store: S) -> &mut Self {
        self.block.attach(store.into());
        self
    }

    pub fn set_hint<S: Into<Cow<'a, str>>>(mut self, hint: S) -> Self {
        self.block.set_hint(hint);
        self
    }

    pub fn set_help<S: Into<Cow<'a, str>>>(mut self, help: S) -> Self {
        self.block.set_help(help);
        self
    }

    pub fn set_name<S: Into<Cow<'a, str>>>(mut self, name: S) -> Self {
        self.block.set_name(name);
        self
    }

    pub fn set_head<S: Into<Cow<'a, str>>>(mut self, head: S) -> Self {
        self.block.set_head(head);
        self
    }

    pub fn set_foot<S: Into<Cow<'a, str>>>(mut self, foot: S) -> Self {
        self.block.set_foot(foot);
        self
    }

    pub fn submit(mut self) {
        if !self.added {
            let block = std::mem::take(&mut self.block);

            self.blocks.push(block);
            self.added = true;
        }
    }
}

impl<'a, 'b> Drop for AddBlock2App<'a, 'b> {
    fn drop(&mut self) {
        if !self.added {
            let block = std::mem::take(&mut self.block);

            self.blocks.push(block);
            self.added = true;
        }
    }
}

pub struct AddCmd2App<'a, 'b, W: Write> {
    cmd: Command<'a>,

    app: &'b mut AppHelp<'a, W>,

    block: Cow<'a, str>,

    added: bool,
}

impl<'a, 'b, W: Write> AddCmd2App<'a, 'b, W> {
    pub fn new<S: Into<Cow<'a, str>>>(app: &'b mut AppHelp<'a, W>, block: S, name: S) -> Self {
        let mut cmd = Command::default();

        cmd.set_name(name);
        Self {
            app,
            cmd,
            block: block.into(),
            added: false,
        }
    }

    pub fn inner(&mut self) -> &mut Command<'a> {
        &mut self.cmd
    }

    pub fn set_name<S: Into<Cow<'a, str>>>(&mut self, name: S) -> &mut Self {
        self.cmd.set_name(name);
        self
    }

    pub fn set_hint<S: Into<Cow<'a, str>>>(&mut self, hint: S) -> &mut Self {
        self.cmd.set_hint(hint);
        self
    }

    pub fn set_help<S: Into<Cow<'a, str>>>(&mut self, help: S) -> &mut Self {
        self.cmd.set_help(help);
        self
    }

    pub fn set_foot<S: Into<Cow<'a, str>>>(&mut self, foot: S) -> &mut Self {
        self.cmd.set_foot(foot);
        self
    }

    pub fn set_head<S: Into<Cow<'a, str>>>(&mut self, head: S) -> &mut Self {
        self.cmd.set_head(head);
        self
    }

    pub fn submit(mut self) {
        if !self.added {
            let store = std::mem::take(&mut self.cmd);

            self.app.add_cmd(self.block.clone(), store).unwrap();
            self.added = true;
        }
    }
}

impl<'a, 'b, W: Write> Drop for AddCmd2App<'a, 'b, W> {
    fn drop(&mut self) {
        if !self.added {
            let store = std::mem::take(&mut self.cmd);

            self.app.add_cmd(self.block.clone(), store).unwrap();
            self.added = true;
        }
    }
}