use std::error::Error;
use std::{env, fs, process};

use eytan_minigrep::{search, search_case_insensitive};

struct Config {
    query: String,
    file_path: String,
    ignore_case: bool
}

impl Config {
    fn build(args: &[String]) -> Result<Self, &str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }
        let query = args[1].clone();
        let file_path = args[2].clone();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Self { query, file_path, ignore_case })
    }
}

fn run(cfg: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(cfg.file_path)?;
    // println!("with text:\n{contents}");

    let results: Box<dyn Iterator<Item = &str>> = if cfg.ignore_case {
        Box::new(search_case_insensitive(&cfg.query, &contents))
    } else {
        Box::new(search(&cfg.query, &contents))
    };

    for line in results {
        println!("{line}")
    }
    Ok(())
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    // println!(
    //     "searching for \"{}\" in file: {}\n",
    //     config.query, config.file_path
    // );

    if let Err(e) = run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}
