1use chrono::{Datelike, Utc};
2use getopts::Options;
3use pyo3::{exceptions::PyValueError, pyfunction, PyResult};
4use std::env;
5
6use crate::renfe::Renfe;
7
8#[pyfunction]
9pub fn main() -> PyResult<()> {
10 let args: Vec<String> = env::args().collect();
11 let program = args[0].clone();
12 let now = Utc::now();
13 let opts = set_opts();
14
15 let matches = match opts.parse(&args[1..]) {
16 Ok(m) => m,
17 Err(f) => {
18 return Err(PyValueError::new_err(f.to_string()));
19 }
20 };
21
22 if matches.opt_present("h") {
23 print_usage(&program, opts);
24 return Ok(());
25 }
26
27 let mut renfe = Renfe::new(matches.opt_present("c"))?;
28
29 let origin = renfe.filter_station(matches.opt_str("f").expect("Missing origin station"))?;
30 let destination =
31 renfe.filter_station(matches.opt_str("t").expect("Missing destination station"))?;
32 let day = match matches.opt_str("d") {
33 Some(day) => day.parse()?,
34 None => now.day(),
35 };
36 let month = match matches.opt_str("m") {
37 Some(day) => day.parse()?,
38 None => now.month(),
39 };
40 let year = match matches.opt_str("y") {
41 Some(day) => day.parse()?,
42 None => now.year(),
43 };
44 let sorted: bool = matches.opt_present("s");
45
46 println!("Today is: {}-{}-{}", now.year(), now.month(), now.day());
47 println!("Searching timetable for date: {}-{}-{}", year, month, day);
48
49 renfe.set_train_schedules(&origin.id, &destination.id, day, month, year, sorted)?;
50
51 println!("Origin station: {}", origin.name);
52 println!("Destination station: {}", destination.name);
53
54 renfe.print_timetable();
55
56 Ok(())
57}
58
59fn print_usage(program: &str, opts: Options) {
60 let brief = format!("Usage: {} [options]", program);
61 print!("{}", opts.usage(&brief));
62}
63
64fn set_opts() -> Options {
65 let mut opts = Options::new();
66 opts.optopt("f", "", "Set From origin station", "ORIGIN");
67 opts.optopt("t", "", "Set To destination station", "DESTINATION");
68 opts.optopt("d", "day", "Set the Day (default: today's day)", "DAY");
69 opts.optopt(
70 "m",
71 "month",
72 "Set the Month (default: today's month)",
73 "MONTH",
74 );
75 opts.optopt("y", "year", "Set the Year (default: today's year)", "YEAR");
76 opts.optflag("s", "sort", "Option to sort the timetable by Duration");
77 opts.optflag("c", "cercanias", "Option to search over Renfe CercanÃas");
78 opts.optflag("h", "help", "Print this help menu");
79
80 opts
81}