use crate::CweDisplayType::{
    Attacks, Consequences, Description, Detections, Extended, Mitigations, Name,
};
use csv::Reader;
use fenir::capec::show_attacks;
use fenir::cve::cve_from_cwe;
use fenir::cwe::CweRecord;
use fenir::database::{
    check_database, criteria_analysis, db_mitre_path, execute_query, find_capec_by_id,
    find_cwe_by_id, find_domain_and_criteria, parse_id_to_u32, prepare_query, search,
    text_or_null, MitreDatabase,
};

use fenir::facilities::{configure_csv_reader, hierarchical_show, ProgressText, Uppercase};
use fenir::package::{
    concepts::simplify_cve_list_content,
    errors::{write_error_message, write_error_message_and_exit},
};
use fenir::query::{build_query, QueryType::ByCwe};
use fenir::{db_mitre, header, section, section_level};
use rusqlite::{params, Connection, Rows};
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use termint::{
    enums::{Color, Modifier},
    widgets::ToSpan,
};
use treelog::{builder::TreeBuilder, Tree};

/// Enum representing different types of CWE information to display
#[derive(Debug)]
pub enum CweDisplayType {
    /// Display all information
    All,
    /// Display related capec
    Attacks,
    /// Display consequences
    Consequences,
    /// Display description
    Description,
    /// Display detection methods
    Detections,
    /// Display extended description
    Extended,
    /// Display mitigation strategies
    Mitigations,
    /// Display cwe name
    Name,
}

impl CweDisplayType {
    pub fn show(&self, cwe_record: &CweRecord) {
        Self::show_record(self, cwe_record);
    }

    fn show_record(cwe_display_type: &CweDisplayType, cwe_record: &CweRecord) {
        match cwe_display_type {
            Description => println!(
                "{} {}",
                format!("{:>5} Description:", "-").fg(Color::DarkBlue),
                cwe_record.description
            ),

            Extended => {
                if !cwe_record.extended.is_empty() {
                    println!(
                        "{} {}",
                        format!("{:>5} Extended:", "-").fg(Color::DarkBlue),
                        cwe_record.extended
                    )
                }
            }

            Attacks => {
                println!();
                section_level!(2, "Attacks");
                show_attacks(cwe_record.attacks.clone());
            }

            Consequences => {
                if !cwe_record.consequences.is_empty() {
                    hierarchical_show("Consequences", cwe_record.clone().consequences)
                }
            }

            Detections => {
                if !cwe_record.detections.is_empty() {
                    hierarchical_show("Detections", cwe_record.clone().detections)
                }
            }

            Mitigations => {
                if !cwe_record.mitigations.is_empty() {
                    hierarchical_show("Mitigations", cwe_record.clone().mitigations)
                }
            }

            Name => print!(""),

            CweDisplayType::All => {
                Self::show_record(&Description, cwe_record);
                Self::show_record(&Extended, cwe_record);
                Self::show_record(&Consequences, cwe_record);
                Self::show_record(&Detections, cwe_record);
                Self::show_record(&Mitigations, cwe_record);
                Self::show_record(&Attacks, cwe_record);
            }
        }
    }
}

/// Injects data from a CSV file into a CWE table in an SQLite database.
///
/// This function connects to the SQLite database specified by `db_mitre_path()` internal method,
/// initializes the `cwe` table if it does not already exist, and reads data
/// from the CSV file specified by `cwe_csv_path` to inject into the `cwe` table.
///
/// # Arguments
///
/// * `cwe_csv_path` - A path the CSV file containing the CWE data.
///
/// # Returns
///
/// This function returns a `Result` with an empty tuple `()` on success, and a boxed `dyn std::error::Error` on failure.
///
/// # Errors
///
/// This function will return an error if:
///
/// * The connection to the SQLite database cannot be established.
/// * The CSV file cannot be read.
/// * Any of the records in the CSV file cannot be parsed correctly.
/// * There is an error executing the SQL insert statement.
///
/// # Dependencies
///
/// This function depends on the `csv` crate for reading CSV files and the `rusqlite` crate for interacting with SQLite databases.
pub fn inject_csv_into_cwe_table(cwe_csv_path: &Path) -> rusqlite::Result<(), Box<dyn Error>> {
    // Open the CSV file and read its content
    let mut reader = configure_csv_reader(cwe_csv_path)?;

    inject_cwe_data(&mut reader)
}

/// Injects CWE (Common Weakness Enumeration) data into an SQLite database.
///
/// This function reads data from a CSV file using a `csv::Reader` and inserts the data into an SQLite database
/// table named `cwe`. The function assumes that the CSV contains the following columns:
/// 1. `id`: CWE ID (i64)
/// 2. `name`: CWE name (String)
/// 3. `description`: CWE description (String)
/// 4. `extended`: Extended information (String)
/// 5. `consequences`: Potential consequences of the weakness (String)
/// 6. `detections`: Ways to detect the weakness (String)
/// 7. `mitigations`: Ways to mitigate the weakness (String)
///
/// # Arguments
///
/// * `conn` - An open SQLite `Connection`.
/// * `reader` - A mutable reference to a `csv::Reader` that reads from a file containing the CWE data.
///
/// # Returns
///
/// This function returns a nested `Result`:
/// * `Ok(Ok(()))` if the data was successfully injected into the database.
/// * `Ok(Err(e))` if there was a problem parsing the CSV records or inserting data into the database.
/// * `Err(e)` if an error occurs while reading the CSV records or executing the database operations.
///
/// # Errors
///
/// This function will return an error if:
/// * There is an error reading the CSV records.
/// * There is an error parsing the CSV data (e.g., converting the `id` column to an `i64`).
/// * There is an error executing the SQL insert statement.
fn inject_cwe_data(reader: &mut Reader<File>) -> rusqlite::Result<(), Box<dyn Error>> {
    let records = reader.records().collect::<rusqlite::Result<Vec<_>, _>>()?;
    let mut progress_bar = ProgressText::new(1, records.len(), String::from("\tCwe table"));

    let connection = db_mitre!()?;
    for record in records {
        progress_bar.progress();

        let _ = connection.execute(
            "INSERT INTO cwe (id, name, description, extended, consequences, detections, mitigations, attacks) VALUES (?1, ?2, ?3, ?4, ?5,?6, ?7, ?8)",
            params![record[0].parse::<i64>()?, record[1].to_string(), record[4].to_string(), text_or_null(record[5].to_string()), record[14].to_string(),
                    text_or_null(record[15].to_string()), text_or_null(record[16].to_string()), text_or_null(record[21].to_string()),],
        );
    }

    println!("\nCWE data injected into SQLite database successfully.");
    Ok(())
}

pub struct GetCweCommand;

impl MitreDatabase for GetCweCommand {
    fn table_definitions(&self) -> HashMap<&'static str, &'static str> {
        HashMap::from([(
            "cwe",
            "CREATE TABLE IF NOT EXISTS cwe (
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL,
                    description TEXT NOT NULL,
                    extended TEXT,
                    consequences TEXT,
                    detections TEXT,
                    mitigations TEXT,
                    attacks TEXT)",
        )])
    }
}

/// Create the tree of the cwe schema. This schema included the list of associated CAPEC and CVE for a cwe record
///
/// # Argument
/// * `cwe` - Cwe record for which the schema must be built
///
/// # Return
/// The tree schema.
///
/// # Example
///
/// ```rust
/// use fenir::database::find_cwe_by_id;
/// use get_cwe::build_tree_schema;
///
/// let cwe = find_cwe_by_id(327).unwrap();
/// let schema = build_tree_schema(&cwe);
///
/// println!("{}", schema.render_to_string())
/// ```
pub fn build_tree_schema(cwe: &CweRecord) -> Tree {
    let mut builder = TreeBuilder::new();
    let cwe_str = format!("CWE-{}", cwe.id);
    builder.node(header!(cwe_str).to_string());

    if check_database("capec").0 {
        builder.node("CAPEC".fg(Color::DarkRed).to_string());
        let capec_ids = parse_id_to_u32(cwe.attacks.clone());
        for capec_id in capec_ids {
            if let Some(capec) = find_capec_by_id(capec_id) {
                builder.leaf(
                    format!("CAPEC-{} - {}", capec_id, capec.name)
                        .fg(Color::DarkRed)
                        .to_string(),
                );
            }
        }

        builder.end();
    }

    builder.node("CVE");
    let cve_results = execute_query(build_query(ByCwe, cwe_str.as_str()));
    let mut cves = cve_from_cwe(&cve_results);
    simplify_cve_list_content(&mut cves);
    if cves.is_empty() {
        builder.leaf("None");
    } else {
        cves.iter().for_each(|x| {
            builder.leaf(x.reference.clone());
        });
    }
    builder.end();

    builder.build()
}

pub fn run_search(args: &[String]) {
    let extraction = find_domain_and_criteria(args);
    if let Some(elements) = extraction {
        let domain = elements.0;
        let criteria = elements.1;

        let crit_analysis = criteria_analysis(criteria.clone());
        let (words, operators) = crit_analysis.unwrap();
        let found = search(
            prepare_query(
                format!("SELECT id FROM cwe WHERE {domain}"),
                words,
                &operators,
            ),
            extract_cwe_records,
        );
        if found.is_empty() {
            write_error_message(
                format!("Domain '{domain}' with criteria '{criteria}' not found").as_str(),
                None,
            );
        }

        found.iter().for_each(|x| {
            println!("{}", x);
            CweDisplayType::show_record(&switch_to_display_type(domain.as_str()), x)
        });
    } else {
        write_error_message_and_exit("Invalid argument: '=' missing. See help.", None);
    }
}

fn switch_to_display_type(name: &str) -> CweDisplayType {
    match name.trim().to_lowercase().as_str() {
        "consequences" => Consequences,
        "detections" => Detections,
        "description" => Description,
        "extended" => Extended,
        "mitigations" => Mitigations,
        "name" => Name,
        _ => CweDisplayType::All,
    }
}

fn extract_cwe_records(rows: &mut Rows) -> Vec<CweRecord> {
    let mut records = Vec::new();
    while let Some(row) = rows.next().unwrap() {
        let result = find_cwe_by_id(row.get(0).unwrap());
        if let Some(result) = result {
            records.push(result);
        }
    }

    records
}

#[cfg(test)]
mod tests {
    use crate::{find_cwe_by_id, inject_csv_into_cwe_table};
    use fenir::cwe::CweRecord;
    use fenir::database::{check_database, refresh_mitre_database, MitreDefinition, MITRE_DB_NAME};
    use fenir::os::{create_tyr_home, find_tyr_home_path};

    fn setup() {
        let tyr_home = find_tyr_home_path();
        if !tyr_home.exists() {
            create_tyr_home(&tyr_home);

            refresh_mitre_database(CweRecord::define(), inject_csv_into_cwe_table);
        }
    }

    #[test]
    fn test_cwe_invalid_none() {
        assert_eq!(None, find_cwe_by_id(10000000));
    }

    #[test]
    fn test_cwe_valid_parameter_not_none() {
        setup();

        assert_ne!(None, find_cwe_by_id(89));
    }

    #[test]
    fn test_cwe_check_database_valid() {
        setup();

        assert!(check_database("cwe").0);
    }

    #[test]
    fn test_cwe_update_csv_reference() {
        setup();

        let tyr_home = find_tyr_home_path();

        assert!(tyr_home.join(MITRE_DB_NAME).exists());
    }

    #[test]
    fn test_cwe_name_valid() {
        let cwe = find_cwe_by_id(112);
        assert_eq!("Missing XML Validation", cwe.unwrap().name);
    }

    #[test]
    fn test_cwe_description_valid() {
        let cwe = find_cwe_by_id(90);

        assert_eq!(
            "The product constructs all or part of an LDAP query using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended LDAP query when it is sent to a downstream component.",
            cwe.unwrap().description
        );
    }

    #[test]
    fn test_cwe_extended_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "Within XML, special elements could include reserved words or characters such as <, >, , and &, which could then be used to add new data or modify XML syntax.",
            cwe.unwrap().extended
        );
    }

    #[test]
    fn test_cwe_id_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(91, cwe.unwrap().id);
    }

    #[test]
    fn test_cwe_consequences_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "::SCOPE:Confidentiality:SCOPE:Integrity:SCOPE:Availability:IMPACT:Execute Unauthorized Code or Commands:IMPACT:Read Application Data:IMPACT:Modify Application Data::",
            cwe.unwrap().consequences
        );
    }

    #[test]
    fn test_cwe_detections_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "::METHOD:Automated Static Analysis:DESCRIPTION:Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect sources (origins of input) with sinks (destinations where the data interacts with external components, a lower layer such as the OS, etc.):EFFECTIVENESS:High::",
            cwe.unwrap().detections
        );
    }

    #[test]
    fn test_cwe_mitigations_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "::PHASE:Implementation:STRATEGY:Input Validation:DESCRIPTION:Assume all input is malicious. Use an accept known good input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, boat may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as red or blue. Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.::",
            cwe.unwrap().mitigations
        );
    }
}
