use std::collections::HashMap;
use crate::utils::{decode_value, encode_value};

pub type ParameterList = HashMap<String, String>;
pub type Parameter = (String, String);

pub fn parameter_find(params: &ParameterList, name: &str) -> Option<String> {
    params.get(name).map(|value| value.clone())
}

pub fn parameter_list_has(params: &ParameterList, key: &str, value: &str, strict: bool) -> bool {
    if let Some(check_value) = params.get(key) {
        if check_value == value && strict {
            return true;
        }
        if check_value.contains(value) && !strict {
            return true;
        }
    }
    return false;
}

pub fn parameter_list_find(param_lists: &Vec<ParameterList>, key: &str, value: &str, strict: bool) -> Option<ParameterList> {
    for params in param_lists {
        if parameter_list_has(params, key, value, strict) {
            return Some(params.clone());
        }
    }
    None
}

pub fn parameter_list_find_all(param_lists: &Vec<ParameterList>, key: &str, value: &str, strict: bool) -> Vec<ParameterList> {
    let mut found = Vec::new();
    for params in param_lists {
        if parameter_list_has(params, key, value, strict) {
            found.push(params.clone())
        }
    }
    found
}

pub fn parameter_parse(params_str: &str) -> ParameterList {
    let parts: Vec<&str> = params_str.split(' ').collect();

    let mut response_params = ParameterList::new();
    parts.iter().for_each(|part| {
        let (key, value) = part.split_once('=').unwrap_or((part, ""));
        response_params.insert(key.to_string(), decode_value(value));
    });

    response_params
}

pub fn parameter_to_string(param: Parameter) -> String {
    format!("{}={}", param.0, encode_value(&param.1))
}

pub fn parameter_list_to_string(parameter_list: ParameterList, sep: &str) -> String {
    parameter_list
        .into_iter()
        .map(|param| parameter_to_string(param))
        .collect::<Vec<String>>()
        .join(sep)
}

pub fn parameters_to_string(parameters: Vec<Parameter>, sep: &str) -> String {
    parameters
        .into_iter()
        .map(|param| parameter_to_string(param))
        .collect::<Vec<String>>()
        .join(sep)
}