use rand::Rng;

const TITLES: [&str; 11] = [
    "/* {} */",
    "# {}",
    "// {}",
    "<!-- {} -->",
    "{# {} #}",
    "-- {}",
    "--[[ {} --]]",
    "; {}",
    "% {}",
    "{- {} -}",
    "(* {} *)",
];

pub fn gen_title() -> String {
    let mut rng = rand::thread_rng();
    let title_fmt = TITLES[rng.gen_range(0..TITLES.len())];
    let title = str::replace(title_fmt, "{}", "CódigoComentado");
    title.to_string()
}

pub fn ascii_table(raw_table: String) -> String {
    let raw_table = raw_table.trim();
    let mut new_table: Vec<Vec<Vec<String>>> = Vec::new();
    let mut max_width: Option<Vec<usize>> = None;
    let mut result = String::new();

    for line in raw_table.lines() {
        let items: Vec<String> = line.split('|').map(|s| s.to_string()).collect();
        let mut new_items: Vec<Vec<String>> = vec![Vec::new(); items.len()];

        if max_width.is_none() {
            max_width = Some(vec![0; items.len()]);
        }

        for (n, item) in items.iter().enumerate() {
            let item = item
                .replace("<b>", "")
                .replace("</b>", "")
                .replace("<pre>", "")
                .replace("</pre>", "")
                .replace("\\", "");
            let split_items: Vec<String> = item.split("<br>").map(|s| s.to_string()).collect();
            new_items[n].clone_from(&split_items);
            let max_local = split_items.iter().map(|s| s.len()).max().unwrap_or(0);
            if let Some(ref mut mw) = max_width {
                mw[n] = std::cmp::max(mw[n], max_local);
            }
        }

        new_table.push(new_items);
    }

    for row in new_table {
        let max_height = row.iter().map(|col| col.len()).max().unwrap_or(0);
        for index in 0..(row.len() * max_height) {
            let index_subrow = index / row.len();
            let index_col = index % row.len();
            let text = if let Some(col) = row.get(index_col) {
                if let Some(text) = col.get(index_subrow) {
                    text
                } else {
                    &String::from("")
                }
            } else {
                &String::from("")
            };
            let text = text.trim_end();
            if let Some(ref mw) = max_width {
                result.push_str(&format!(
                    "{:width$}{}",
                    text,
                    if index_col < row.len() - 1 { "|" } else { "\n" },
                    width = mw[index_col]
                ));
            }
        }
    }

    format!("```\n{}\n```\n", result)
}