use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread::spawn;

use cursive::view::{Nameable, Resizable, Scrollable};
use cursive::views::{LinearLayout, NamedView, ResizedView, ScrollView};
use cursive::views::{Panel, TextView};
use cursive::Cursive;
use cursive_logger_view::{CursiveLogWriter, FlexiLoggerView};
use cursive_table_view::TableView;
use cursive_tabs::TabPanel;
use cursive_tree_view::Placement;
use cursive_tree_view::TreeView;
use flexi_logger::Logger;
use libntdsextract2::{CDatabase, EntryId, ObjectTreeEntry};

mod acl_column;
mod acl_line;
mod attribute_column;
mod attribute_line;
mod attribute_line_set;
mod entry_attributes;
mod tree_entry;

use attribute_column::*;
use attribute_line::*;
use entry_attributes::*;
use tree_entry::*;

use crate::walk::acl_column::AclColumn;
use crate::walk::acl_line::AclLine;

const TREE: &str = "tree_view";
const ATTRIBUTES: &str = "Attributes";
const ACL: &str = "Access Control List";
const SACL: &str = "SACL";
const DACL: &str = "DACL";
const LEFT_PANEL: &str = "left_panel";
const RIGHT_PANEL: &str = "right_panel";
const LAYOUT: &str = "layout";
const LOG_VIEW: &str = "log_view";

pub fn run_tui<'db, 'info>(database: CDatabase<'db, 'info>) -> anyhow::Result<()> {
    let mut tree_view = TreeView::new();
    insert_item(&mut tree_view, Arc::clone(database.object_tree().root()), 0);

    // because CDatabase is neither Send nor Sync, we leave it in the current
    // thread and move all the UI stuff to other threads
    let (tx_entry_id, rx_entry_id) = channel();
    let (tx_attribs, rx_attribs) = channel();
    let ui_thread = spawn(move || {
        ui_thread_fn(
            tree_view,
            Arc::new(Mutex::new(tx_entry_id)),
            Arc::new(Mutex::new(rx_attribs)),
        )
    });

    // from this point on, the current threads work as a data provider server
    // for the ui thread
    loop {
        match rx_entry_id.recv() {
            Ok(entry_id) => {
                let attributes = EntryAttributes::new(&database, entry_id);

                if tx_attribs.send(attributes).is_err() {
                    drop(rx_entry_id);
                    break;
                }
            }
            Err(_) => {
                drop(tx_attribs);
                break;
            }
        }
    }
    let _ = ui_thread.join();
    Ok(())
}

fn insert_item(tree_view: &mut TreeView<TreeEntry>, item: Arc<ObjectTreeEntry>, row: usize) {
    if item.children().lock().unwrap().is_empty() {
        tree_view.insert_item(TreeEntry::from(item), Placement::LastChild, row);
    } else {
        let row = tree_view
            .insert_container_item(
                TreeEntry::from(Arc::clone(&item)),
                Placement::LastChild,
                row,
            )
            .unwrap_or(0);
        // inserting elements in collapsed containers does not work
        tree_view.set_collapsed(row, false);
        let children = item.children().lock().unwrap();
        let mut sorted_children: Vec<_> = children.iter().collect();
        sorted_children.sort();
        for child in sorted_children {
            insert_item(tree_view, Arc::clone(child), row);
        }
        tree_view.set_collapsed(row, true);
    }
}

fn ui_thread_fn(
    mut tree_view: TreeView<TreeEntry>,
    tx_entry_id: Arc<Mutex<Sender<EntryId>>>,
    rx_attribs: Arc<Mutex<Receiver<EntryAttributes>>>,
) {
    let mut siv = cursive::default();

    Logger::try_with_env_or_str("warn")
        .expect("Could not create Logger from environment :(")
        // Configure logging to both file and Cursive
        .log_to_writer(
            // Create Cursive log writer and box it for dynamic dispatch
            CursiveLogWriter::new(&siv)
                //// Optional format configuration (commented out example)
                // .with_format({
                //     use cursive_logger_view::LogItems::*;
                //     [Level, DateTime, ModLine, Message]
                //         .into_iter()
                //         .collect()
                // })
                // .with_time_format("%T%.6f".into())
                .into_boxed(),
        )
        .start()
        .unwrap();

    let attributes: TableView<AttributeLine, AttributeColumn> = TableView::new()
        .column(AttributeColumn::Name, "Name", |c| {
            c.align(cursive::align::HAlign::Left).width(33)
        })
        .column(AttributeColumn::Value, "Value", |c| {
            c.align(cursive::align::HAlign::Left)
        })
        .default_column(AttributeColumn::Name);

    let dacls: TableView<AclLine, AclColumn> = TableView::new()
        .column(AclColumn::SubjectName, "Subject", |c| {
            c.align(cursive::align::HAlign::Left).width(46)
        })
        .column(AclColumn::Operation, "Operation", |c| {
            c.align(cursive::align::HAlign::Left).width(10)
        })
        .column(AclColumn::AccessMask, "AccessMask", |c| {
            c.align(cursive::align::HAlign::Left).width(40)
        })
        .column(AclColumn::ExtendedRight, "Extended Right", |c| {
            c.align(cursive::align::HAlign::Left)
        });

    let sacls: TableView<AclLine, AclColumn> = TableView::new()
        .column(AclColumn::SubjectName, "Subject", |c| {
            c.align(cursive::align::HAlign::Left).width(46)
        })
        .column(AclColumn::Operation, "Operation", |c| {
            c.align(cursive::align::HAlign::Left).width(10)
        })
        .column(AclColumn::AccessMask, "AccessMask", |c| {
            c.align(cursive::align::HAlign::Left).width(40)
        })
        .column(AclColumn::ExtendedRight, "Extended Right", |c| {
            c.align(cursive::align::HAlign::Left)
        });
    const ACL_FLAGS_HELP: [(&str, &str); 20] = [
        ("GR", "Generic Read"),
        ("GW", "Generic Write"),
        ("GX", "Generic Execute"),
        ("GA", "Generic All"),
        ("MA", "Maximum Allowed"),
        ("AS", "Access System Security"),
        ("SY", "Synchronize"),
        ("WO", "Write Owner"),
        ("WD", "Write DACL"),
        ("RC", "Read Control"),
        ("SD", "Standard Delete"),
        ("CR", "Control Access"),
        ("LO", "List Object"),
        ("DT", "Delete Tree"),
        ("WP", "Write Property"),
        ("RP", "Read Property"),
        ("SW", "Self Write"),
        ("LC", "List Children"),
        ("DC", "Delete Child"),
        ("CC", "Create Child"),
    ];
    const ACL_FLAGS_COLUMNS: usize = 4;
    let mut acl_info_text = String::new();
    for (index, (short, long)) in ACL_FLAGS_HELP.into_iter().enumerate() {
        acl_info_text.push_str(&format!("{short} ... {long:25}"));
        if index % ACL_FLAGS_COLUMNS == ACL_FLAGS_COLUMNS - 1 {
            acl_info_text.push('\n');
        }
    }
    let acl_info = TextView::new(acl_info_text);

    siv.add_global_callback('q', |s| s.quit());
    siv.add_global_callback('+', enlarge_tree);
    siv.add_global_callback('-', shrink_tree);

    let tx_entry_id_on_select = Arc::clone(&tx_entry_id);
    let rx_attribs_on_select = Arc::clone(&rx_attribs);
    tree_view.set_on_select(move |siv, row| {
        let tx_entry_id = Arc::clone(&tx_entry_id_on_select);
        let rx_attribs = Arc::clone(&rx_attribs_on_select);
        on_select(siv, row, tx_entry_id, rx_attribs)
    });

    let acl = LinearLayout::vertical()
        .child(
            Panel::new(dacls.with_name(DACL))
                .title("Discretionary ACL")
                .full_screen(),
        )
        .child(
            Panel::new(sacls.with_name(SACL))
                .title("System ACL")
                .full_screen(),
        )
        .child(
            Panel::new(acl_info.fixed_height(ACL_FLAGS_HELP.len() / ACL_FLAGS_COLUMNS))
                .title("SDDL abbreviations for access mask flags"),
        );

    let mut tab_panel = TabPanel::new()
        .with_tab(attributes.with_name(ATTRIBUTES))
        .with_tab(acl.with_name(ACL));
    tab_panel.set_active_tab(ATTRIBUTES).unwrap();

    let tree_view_width = 60;
    let ntds_view = LinearLayout::horizontal()
        .child(
            Panel::new(tree_view.with_name(TREE).scrollable())
                .fixed_width(tree_view_width)
                .with_name(LEFT_PANEL),
        )
        .child(tab_panel.full_screen().with_name(RIGHT_PANEL))
        .with_name(LAYOUT)
        .full_screen();
    let data_and_logview = LinearLayout::vertical()
        .child(ntds_view)
        .child(
            Panel::new(
                FlexiLoggerView::new()
                    .wrap_scroll_view()
                    .with_name(LOG_VIEW)
                    .fixed_height(10),
            )
            .title("Error log")
            .title_position(cursive::align::HAlign::Left),
        )
        .full_screen();
    siv.set_user_data(tree_view_width);

    siv.add_layer(data_and_logview);

    // initially select the first item
    on_select(
        &mut siv,
        0,
        Arc::clone(&tx_entry_id),
        Arc::clone(&rx_attribs),
    );
    siv.run();
    if let Ok(tx) = tx_entry_id.lock() {
        drop(tx)
    }
    if let Ok(rx) = rx_attribs.lock() {
        drop(rx)
    }
}

fn on_select(
    siv: &mut Cursive,
    row: usize,
    tx_entry_id: Arc<Mutex<Sender<EntryId>>>,
    rx_attribs: Arc<Mutex<Receiver<EntryAttributes>>>,
) {
    let tree_view = siv.find_name::<TreeView<TreeEntry>>(TREE).unwrap();
    if let Some(entry) = tree_view.borrow_item(row) {
        match tx_entry_id.lock() {
            Ok(tx) => {
                if tx
                    .send(EntryId::Id(*entry.entry().record_ptr().ds_record_id()))
                    .is_err()
                {
                    log::error!("unable to send record ID");
                    siv.quit();
                    return;
                }
            }
            _ => {
                log::error!("unable to acquire sender lock");
                siv.quit();
                return;
            }
        }

        match rx_attribs.lock() {
            Ok(rx) => match rx.recv() {
                Ok(entry_attributes) => {
                    let (attribs, dacls, sacls) = entry_attributes.explode();
                    let attribs = attribs.into_iter().flat_map(|s| s.into_lines()).collect();

                    let mut attributes_table = siv
                        .find_name::<TableView<AttributeLine, AttributeColumn>>(ATTRIBUTES)
                        .unwrap();
                    attributes_table.set_items(attribs);
                    attributes_table.set_selected_row(0);

                    let mut acl_table = siv
                        .find_name::<TableView<AclLine, AclColumn>>(DACL)
                        .unwrap();
                    acl_table.set_items(dacls);
                    acl_table.set_selected_row(0);

                    let mut acl_table = siv
                        .find_name::<TableView<AclLine, AclColumn>>(SACL)
                        .unwrap();
                    acl_table.set_items(sacls);
                    acl_table.set_selected_row(0);
                }
                Err(_) => {
                    siv.quit();
                }
            },
            _ => {
                log::error!("unable to acquire receiver lock");
                siv.quit();
            }
        }
    }
}

fn enlarge_tree(siv: &mut Cursive) {
    let mut left_panel = siv
        .find_name::<ResizedView<Panel<ScrollView<NamedView<TreeView<TreeEntry>>>>>>(LEFT_PANEL)
        .unwrap();
    siv.with_user_data(move |tree_view_width| {
        *tree_view_width += 1;
        left_panel.set_width(cursive::view::SizeConstraint::Fixed(*tree_view_width));
    });
}

fn shrink_tree(siv: &mut Cursive) {
    let mut left_panel = siv
        .find_name::<ResizedView<Panel<ScrollView<NamedView<TreeView<TreeEntry>>>>>>(LEFT_PANEL)
        .unwrap();
    siv.with_user_data(move |tree_view_width| {
        *tree_view_width -= 1;
        left_panel.set_width(cursive::view::SizeConstraint::Fixed(*tree_view_width));
    });
}
