use crate::{cli, storage};

#[derive(Clone)]
pub struct Field {
    pub matches: i32,
    pub file: String,
}

pub fn search(s: String) {
    let binding = s.to_lowercase();
    let search_tokens: Vec<&str> = binding.split(' ').collect();

    let titles: Vec<String> = storage::get_note_titles();
    let mut result: Vec<Field> = Vec::new();

    for title in titles {
        let title_tokens: Vec<&str> = title.split(' ').collect();
        let mut count = 0;

        for title_token in &title_tokens {
            for search_token in &search_tokens {
                if title_token == search_token {
                    count += 1;
                }
            }
        }

        result.push(Field {
            matches: count,
            file: title,
        });
    }

    let n = result.len();
    let mut temp;
    for i in 0..(n - 1) {
        for j in 0..(n - i - 1) {
            if result[j].matches < result[j + 1].matches {
                temp = result[j].clone();
                result[j] = result[j + 1].clone();
                result[j + 1] = temp;
            }
        }
    }

    let mut search_results = Vec::new();
    for item in result {
        if item.matches != 0 {
            search_results.push(item);
        } else {
            break;
        }
    }

    cli::search_result(search_results);
}
