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
use crate::{
    get_executable_directory,
    program_info::{PROGRAM_AUTHORS, PROGRAM_DESCRIPTION, PROGRAM_NAME},
    weather::{api_setup, check, search_city},
};
use clap::{Parser, Subcommand};

const ABOUT: &str = "# weather-cli : Weather for command-line fans!";

#[derive(Parser)]
#[command(author, version, about = ABOUT, long_about = None)]
struct Cli {
    /// Optional name to operate on
    name: Option<String>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Check weather information in your city.
    Check {},

    /// Search and set your city.
    SetLocation {
        /// A search query.
        #[arg(short, long)]
        query: String,
    },

    /// Setup the OpenWeather API Key
    ApiSetup {
        /// API key from OpenWeather.
        #[arg(short, long)]
        key: String,
    },

    /// View information about the program.
    About {},
}

/// Initialize the command line interface.
pub async fn init() {
    let cli = Cli::parse();

    match &cli.command {
        Some(Commands::Check {}) => {
            match check().await {
                Ok(()) => {}
                Err(e) => {
                    println!("ERROR: {}", e);
                    if e.to_string().contains("No such file or directory") {
                        println!("ERROR: Try checking if \"settings.json\" exists. If not, you can create one with \"set-location\" command.");
                    }
                }
            };
        }
        Some(Commands::SetLocation { query }) => {
            search_city(query).await.unwrap();
        }
        Some(Commands::ApiSetup { key }) => {
            api_setup(key.to_string()).unwrap();
        }
        Some(Commands::About {}) => {
            let splited_author_list: Vec<&str> = PROGRAM_AUTHORS.split(',').collect();

            let mut authors = String::new();
            for (index, one) in splited_author_list.into_iter().enumerate() {
                if index == 0 {
                    authors += one.trim();
                } else {
                    authors = authors + ", " + one.trim();
                }
            }

            println!("# {}:", PROGRAM_NAME);
            println!("{}\n", PROGRAM_DESCRIPTION);
            println!("Developed by: {}", authors);
        }
        None => {
            println!("Please use \"weather-cli help\" command for help.");

            let executable_directory = get_executable_directory().unwrap();
            println!("Program Executable Directory: {}", executable_directory);
        }
    }
}