use std::env;
use std::fs::{self, File};
//use std::path::Path;
//use std::io::BufReader;
//use std::io::stdout;
//use std::io::prelude::*;

fn main(){
    let args: Vec<String> = env::args().collect();
    let mut pattern_and_filename: Vec<String> = Vec::new(); // 0 - pattern, 1 - name of files
    let mut invert: bool = false;
    
    for arg in 1..args.len() {
        match args[arg].as_str() {
            "--help" => {
                println!("Usage: grep [OPTIONS] FILE");
                println!("Print lines matching a pattern");
                return;
            },
            "-v" => {
                invert = true;
            },
            arg => {
                if args.len() < 3 {
                    println!("grep: Not enought arguments");
                    return;
                }      
                pattern_and_filename.push(arg.to_string());
            },
        }
    }
    let pattern = &pattern_and_filename[0];
    let filename = &pattern_and_filename[1];
    let contents = fs::read_to_string(&filename);
    for line in search(pattern.to_string(), contents.unwrap().as_str(), invert) {
        println!("{}", line);
    }
}

fn search<'a>(pattern: String, contents: &'a str, invert: bool) -> Vec<&'a str> {
    let mut results = Vec::new();
    for line in contents.lines() {
        if line.contains(&pattern) && !invert {
            results.push(line);
        } 
        else if !line.contains(&pattern) && invert {
            results.push(line);
        }
    }
    results
}
