1use crate::argsparsing::ArgsP;
2use crate::engine::structs::{BasicHandler, CmdInfoCmd, CmdInfoSubcmd, CmdMap, Engine, ErrorType, SubCmdsMap};
3use std::collections::HashMap;
4use std::{env};
5
6pub struct EngineGetter<'a> {
7 pub e: &'a Engine<'a>
8}
9
10impl<'a> EngineGetter<'a> {
11 pub fn new(e: &'a Engine<'a>) -> Self {
12 Self { e: e }
13 }
14
15 pub fn get_cmds(&self) -> &CmdMap<'a> {
16 return &self.e.cmds;
17 }
18
19 pub fn get_subcmds(&self) -> &SubCmdsMap<'a> {
20 return &self.e.subcmds;
21 }
22
23 pub fn basic_handler(&self) -> &BasicHandler<'a> {
24 return &self.e.basic_handler;
25 }
26}
27
28impl<'a> Engine<'a> {
29 pub fn new(args_p: &'a mut ArgsP, about: String) -> Self {
30 Self {
31 args_p,
32 cmds: HashMap::new(),
33 subcmds: HashMap::new(),
34 basic_handler: None,
35 about: about,
36 }
37 }
38
39 pub fn getter(&'a self) -> EngineGetter<'a> {
40 return EngineGetter::new(self);
41 }
42
43 pub fn new_command(&mut self, name: &'a str, cmdinfo: CmdInfoCmd<'a>) {
44 self.cmds.insert(name, cmdinfo);
45 }
46
47 pub fn new_commands(&mut self, names: Vec<&'a str>, cmdinfo: CmdInfoCmd<'a>) {
48 for name in names {
49 self.new_command(name, cmdinfo.clone());
50 }
51 }
52
53 pub fn new_subcommand(&mut self, name: &'a str, cmdinfo: CmdInfoSubcmd<'a>) {
54 self.subcmds.insert(name, cmdinfo);
55 }
56
57 pub fn new_subcommands(&mut self, names: Vec<&'a str>, cmdinfo: CmdInfoSubcmd<'a>) {
58 for name in names {
59 self.new_subcommand(name, cmdinfo.clone());
60 }
61 }
62
63 pub fn work(&mut self, args: &[&str]) -> ErrorType {
64 self.args_p.parse_agrs_to_self(args);
65 if self.args_p.args.is_empty() {
66 println!("{}", self.about);
67 return Err("No command provided".into());
68 }
69 let all_args = self.args_p.args.clone();
70 let cmd = all_args[0].as_str();
71 let args_refs: Vec<&str> = all_args[1..].iter().map(|s| s.as_str()).collect();
72 self.process(cmd, &args_refs)
73 }
74
75 pub fn main(&mut self) -> ErrorType {
76 self.work(
77 &env::args()
78 .collect::<Vec<_>>()
79 .iter()
80 .map(|s| s.as_str())
81 .collect::<Vec<_>>()[1..],
82 )
83 }
84}