/*
 * meli - bin.rs
 *
 * Copyright 2017-2018 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

//!
//!  This crate contains the frontend stuff of the application. The application entry way on
//!  `src/bin.rs` creates an event loop and passes input to a thread.
//!
//! The mail handling stuff is done in the `melib` crate which includes all backend needs. The
//! split is done to theoretically be able to create different frontends with the same innards.
//!

#[allow(unused_variables)]
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
extern crate wee_alloc;
#[cfg(feature = "wee_alloc")]
#[global_allocator]
#[cfg(feature = "wee_alloc")]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

mod helpers {
    use wasm_bindgen::prelude::*;
    #[wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = console)]
        pub fn log(s: &str);
    }

    pub use log as js_console;

    pub static ENRON_CONFIG: &'static str = r#"
[accounts.enron]
root_mailbox = "ermis-f"
format = "demo"
index_style = "compact" # or [plain, threaded, compact]
identity="frank.ermis@enron.com"
display_name = "Frank Ermis"
subscribed_mailboxes = ["*"]
mailboxes."INBOX/Python".listing.index_style = "conversations"

[composing]
# required for sending e-mail
send_mail = '/bin/true'
    "#;
}

pub use helpers::*;
#[wasm_bindgen]
pub fn greet() {
    js_console("Hello, wasm-game-of-life!");
}

use std::sync::{Arc, Mutex};
//use js_sys::{Array, Date};
//use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::CustomEvent;

use std::collections::VecDeque;
use std::path::PathBuf;
extern crate xdg_utils;
#[macro_use]
extern crate serde_derive;
extern crate linkify;
extern crate uuid;

extern crate bitflags;
extern crate serde_json;
extern crate smallvec;

#[macro_use]
extern crate melib;
use melib::*;

#[macro_use]
pub mod types;
use crate::types::*;

#[macro_use]
pub mod terminal;
use crate::terminal::*;

#[macro_use]
pub mod execute;
use crate::execute::*;

pub mod state;
use crate::state::*;

pub mod components;
use crate::components::*;

#[macro_use]
pub mod conf;
use crate::conf::*;

//pub mod workers;
//use crate::workers::*;
pub mod pool;
use crate::pool::*;

#[cfg(feature = "sqlite3")]
pub mod sqlite3;

pub mod jobs;
pub mod mailcap;
//pub mod plugins;

//use nix;
//use std::os::raw::c_int;

// Called by our JS entry point to run the example
#[wasm_bindgen(start)]
pub fn run() -> std::result::Result<(), JsValue> {
    extern crate console_error_panic_hook;
    std::panic::set_hook(Box::new(console_error_panic_hook::hook));

    // Use `web_sys`'s global `window` function to get a handle on the global
    // window object.
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");

    // Manufacture the element we're gonna append
    let val = document.query_selector("div#terminal")?.unwrap();
    val.set_inner_html("Loading terminal from inside Rust!");
    if let Some(val) = wasm_bindgen::JsCast::dyn_ref::<web_sys::HtmlElement>(&val) {
        val.set_tab_index(1);
    }
    //let (sender, receiver) = crossbeam::channel::bounded(32 * ::std::mem::size_of::<ThreadEvent>());
    let state = Arc::new(Mutex::new(
        State::new(
            None, //Some(Settings::without_accounts().unwrap_or_default()),
                 //sender, receiver,
        )
        .unwrap(),
    ));

    {
        let cb = Closure::wrap(Box::new(move |event: web_sys::Event| {
            js_console("cb focus?");
            let target = event.target();
            if let Some(val) = target
                .as_ref()
                .and_then(|target| wasm_bindgen::JsCast::dyn_ref::<web_sys::HtmlElement>(target))
            {
                js_console("focus!");

                js_console(&format!("{:?}", val.focus()));
            }
        }) as Box<dyn FnMut(_)>);

        val.add_event_listener_with_callback("touchend", cb.as_ref().unchecked_ref())
            .unwrap();
        cb.forget(); // TODO cycle collect
    }
    {
        let state = state.clone();
        let cb = Closure::wrap(Box::new(move |event: web_sys::Event| {
            if let Some(key_e) = wasm_bindgen::JsCast::dyn_ref::<web_sys::KeyboardEvent>(&event) {
                let mut state_lck = state.lock().unwrap();
                js_console(&format!("key event {:?}", key_e));
                let k = Key::from(key_e);
                match state_lck.mode {
                    UIMode::Normal => match k {
                        Key::Char('q') | Key::Char('Q') => {
                            state_lck.context.replies.push_back(UIEvent::StatusEvent(
                                StatusEvent::DisplayMessage(
                                    "Can't quit. Just close the browser tab.".to_string(),
                                ),
                            ));
                            state_lck.redraw();
                        }
                        Key::Char(' ') => {
                            state_lck.mode = UIMode::Execute;
                            state_lck.rcv_event(UIEvent::ChangeMode(UIMode::Execute));
                            state_lck.redraw();
                        }
                        key => {
                            state_lck.rcv_event(UIEvent::Input(key));
                            state_lck.redraw();
                        }
                    },
                    UIMode::Insert => match k {
                        Key::Char('\n') | Key::Esc => {
                            state_lck.mode = UIMode::Normal;
                            state_lck.rcv_event(UIEvent::ChangeMode(UIMode::Normal));
                            state_lck.redraw();
                        }
                        k => {
                            state_lck.rcv_event(UIEvent::InsertInput(k));
                            state_lck.redraw();
                        }
                    },
                    UIMode::Execute => match k {
                        Key::Char('\n') | Key::Esc => {
                            state_lck.mode = UIMode::Normal;
                            state_lck.rcv_event(UIEvent::ChangeMode(UIMode::Normal));
                            state_lck.redraw();
                        }
                        k => {
                            state_lck.rcv_event(UIEvent::ExInput(k));
                            state_lck.redraw();
                        }
                    },
                    UIMode::Embed => {
                        state_lck.rcv_event(UIEvent::EmbedInput((k, vec![])));
                        state_lck.redraw();
                    }
                    UIMode::Fork => {
                        unreachable!("Should not fork in WASM");
                    }
                }
                let events: smallvec::SmallVec<[UIEvent; 8]> = state_lck.context.replies();
                if !events.is_empty() {
                    for e in events {
                        state_lck.rcv_event(e);
                    }
                    state_lck.redraw();
                }
            } else {
                js_console(&format!("not key event {:?}", event));
            }
        }) as Box<dyn FnMut(_)>);

        val.add_event_listener_with_callback("keydown", cb.as_ref().unchecked_ref())
            .unwrap();
        cb.forget(); // TODO cycle collect
    }
    {
        let state = state.clone();
        let cb = Closure::wrap(Box::new(move |event: web_sys::Event| {
            if let Some(customevent) = wasm_bindgen::JsCast::dyn_ref::<CustomEvent>(&event) {
                if customevent
                    .detail()
                    .as_string()
                    .as_ref()
                    .map(|s| s.as_str())
                    == Some("resize")
                {
                    let mut state_lck = state.lock().unwrap();
                    state_lck.update_size();
                    state_lck.render();
                    state_lck.redraw();
                } else {
                    let b: Box<ThreadEvent> = unsafe {
                        Box::from_raw(
                            customevent.detail().as_f64().unwrap() as u32 as *mut ThreadEvent
                        )
                    };
                    js_console(&format!("thread event {:?}", b));
                    if let ThreadEvent::UIEvent(e) = *b {
                        let mut state_lck = state.lock().unwrap();
                        js_console(&format!("thread event {:?}", e));
                        state_lck.rcv_event(e);
                        state_lck.redraw();
                        let events: smallvec::SmallVec<[UIEvent; 8]> = state_lck.context.replies();
                        if !events.is_empty() {
                            for e in events {
                                state_lck.rcv_event(e);
                            }
                            state_lck.redraw();
                        }
                    }
                }
            } else {
                js_console(&format!("not thread event {:?}", event));
            }
        }) as Box<dyn FnMut(_)>);

        val.add_event_listener_with_callback("meli-event", cb.as_ref().unchecked_ref())
            .unwrap();
        cb.forget(); // TODO cycle collect
    }

    let bytes = include_bytes!("../enron_chain_mail.eml");
    let wrapper = EnvelopeWrapper::new(bytes.to_vec()).unwrap();

    let mut state_lck = state.lock().unwrap();

    let window = Box::new(Tabbed::new(
        vec![
            Box::new(listing::Listing::new(&mut state_lck.context)),
            Box::new(ContactList::new(&state_lck.context)),
            Box::new(StatusPanel::new(crate::conf::value(
                &state_lck.context,
                "theme_default",
            ))),
            Box::new(EnvelopeView::new(wrapper, None, None, 0)),
        ],
        &state_lck.context,
    ));

    let status_bar = Box::new(StatusBar::new(window));
    state_lck.register_component(status_bar);
    state_lck.render();
    state_lck.redraw();
    /*

    {
            let closure: Closure<FnMut(_)> = Closure::new(move |event: web_sys::MouseEvent| {
            context.begin_path();
            context.move_to(event.offset_x() as f64, event.offset_y() as f64);
            pressed.set(true);
        });
        (canvas.as_ref() as &web_sys::EventTarget)
            .add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref())
            .unwrap();
        closure.forget();
    }
    */
    Ok(())
}

fn parse_manpage(src: &str) -> Result<ManPages> {
    match src {
        "" | "meli" | "main" => Ok(ManPages::Main),
        "meli.conf" | "conf" | "config" | "configuration" => Ok(ManPages::Conf),
        "meli-themes" | "themes" | "theming" | "theme" => Ok(ManPages::Themes),
        _ => Err(MeliError::new(format!(
            "Invalid documentation page: {}",
            src
        ))),
    }
}

use structopt::StructOpt;

#[derive(Debug)]
/// Choose manpage
enum ManPages {
    /// meli(1)
    Main = 0,
    /// meli.conf(5)
    Conf = 1,
    /// meli-themes(5)
    Themes = 2,
}

#[derive(Debug, StructOpt)]
#[structopt(name = "meli", about = "terminal mail client", version_short = "v")]
struct Opt {
    /// use specified configuration file
    #[structopt(short, long, parse(from_os_str))]
    config: Option<PathBuf>,

    #[structopt(subcommand)]
    subcommand: Option<SubCommand>,
}

#[derive(Debug, StructOpt)]
enum SubCommand {
    /// print default theme in full to stdout and exit.
    PrintDefaultTheme,
    /// print loaded themes in full to stdout and exit.
    PrintLoadedThemes,
    /// create a sample configuration file with available configuration options. If PATH is not specified, meli will try to create it in $XDG_CONFIG_HOME/meli/config.toml
    #[structopt(display_order = 1)]
    CreateConfig {
        #[structopt(value_name = "NEW_CONFIG_PATH", parse(from_os_str))]
        path: Option<PathBuf>,
    },
    /// test a configuration file for syntax issues or missing options.
    #[structopt(display_order = 2)]
    TestConfig {
        #[structopt(value_name = "CONFIG_PATH", parse(from_os_str))]
        path: Option<PathBuf>,
    },
    #[structopt(visible_alias="docs", aliases=&["docs", "manpage", "manpages"])]
    #[structopt(display_order = 3)]
    /// print documentation page and exit (Piping to a pager is recommended.).
    Man(ManOpt),

    /// View mail from input file.
    View {
        #[structopt(value_name = "INPUT", parse(from_os_str))]
        path: PathBuf,
    },
}

#[derive(Debug, StructOpt)]
struct ManOpt {
    #[structopt(default_value = "meli", possible_values=&["meli", "conf", "themes"], value_name="PAGE", parse(try_from_str = parse_manpage))]
    page: ManPages,
}

fn _main() {
    let opt = Opt::from_args();
    ::std::process::exit(match _run_app(opt) {
        Ok(()) => 0,
        Err(err) => {
            eprintln!("{}", err);
            1
        }
    });
}

fn _run_app(opt: Opt) -> Result<()> {
    if let Some(config_location) = opt.config.as_ref() {
        std::env::set_var("MELI_CONFIG", config_location);
    }

    match opt.subcommand {
        Some(SubCommand::TestConfig { path }) => {
            let config_path = if let Some(path) = path {
                path
            } else {
                crate::conf::get_config_file()?
            };
            conf::FileSettings::validate(config_path)?;
            return Ok(());
        }
        Some(SubCommand::CreateConfig { path }) => {
            let config_path = if let Some(path) = path {
                path
            } else {
                crate::conf::get_config_file()?
            };
            if config_path.exists() {
                return Err(MeliError::new(format!(
                    "File `{}` already exists.\nMaybe you meant to specify another path?",
                    config_path.display()
                )));
            }
            conf::create_config_file(&config_path)?;
            return Ok(());
        }
        #[cfg(feature = "cli-docs")]
        Some(SubCommand::Man(manopt)) => {
            let _page = manopt.page;
            const MANPAGES: [&'static str; 3] = [
                include_str!(concat!(env!("OUT_DIR"), "/meli.txt")),
                include_str!(concat!(env!("OUT_DIR"), "/meli.conf.txt")),
                include_str!(concat!(env!("OUT_DIR"), "/meli-themes.txt")),
            ];
            println!("{}", MANPAGES[_page as usize]);
            return Ok(());
        }
        #[cfg(not(feature = "cli-docs"))]
        Some(SubCommand::Man(_manopt)) => {
            return Err(MeliError::new("error: this version of meli was not build with embedded documentation. You might have it installed as manpages (eg `man meli`), otherwise check https://meli.delivery"));
        }
        Some(SubCommand::PrintLoadedThemes) => {
            let s = conf::FileSettings::new()?;
            print!("{}", s.terminal.themes.to_string());
            return Ok(());
        }
        Some(SubCommand::PrintDefaultTheme) => {
            print!("{}", conf::Themes::default().key_to_string("dark", false));
            return Ok(());
        }
        Some(SubCommand::View { ref path }) => {
            if !path.exists() {
                return Err(MeliError::new(format!(
                    "`{}` is not a valid path",
                    path.display()
                )));
            } else if !path.is_file() {
                return Err(MeliError::new(format!(
                    "`{}` is a directory",
                    path.display()
                )));
            }
        }
        None => {}
    }

    /* Create a channel to communicate with other threads. The main process is the sole receiver.
     * */
    let (sender, receiver) = crossbeam::channel::bounded(32 * ::std::mem::size_of::<ThreadEvent>());
    /* Create the application State. */
    let mut state;

    if let Some(SubCommand::View { path }) = opt.subcommand {
        let bytes = std::fs::read(&path)
            .chain_err_summary(|| format!("Could not read from `{}`", path.display()))?;
        let wrapper = EnvelopeWrapper::new(bytes)
            .chain_err_summary(|| format!("Could not parse `{}`", path.display()))?;
        state = State::new(
            Some(Settings::without_accounts().unwrap_or_default()),
            //sender,
            //receiver.clone(),
        )?;
        state.register_component(Box::new(EnvelopeView::new(wrapper, None, None, 0)));
    } else {
        state = State::new(None)?; //, sender, receiver.clone())?;
        #[cfg(feature = "svgscreenshot")]
        state.register_component(Box::new(components::svg::SVGScreenshotFilter::new()));
        let window = Box::new(Tabbed::new(
            vec![
                Box::new(listing::Listing::new(&mut state.context)),
                Box::new(ContactList::new(&state.context)),
                Box::new(StatusPanel::new(crate::conf::value(
                    &state.context,
                    "theme_default",
                ))),
            ],
            &state.context,
        ));

        let status_bar = Box::new(StatusBar::new(window));
        state.register_component(status_bar);

        //let xdg_notifications = Box::new(components::notifications::XDGNotifications::new());
        //state.register_component(xdg_notifications);
        //state.register_component(Box::new(components::notifications::NotificationFilter {}));
    }

    /* Keep track of the input mode. See UIMode for details */
    'main: loop {
        state.render();

        'inner: loop {
            /* Check if any components have sent reply events to State. */
            let events: smallvec::SmallVec<[UIEvent; 8]> = state.context.replies();
            for e in events {
                state.rcv_event(e);
            }
            state.redraw();

            /* Poll on all channels. Currently we have the input channel for stdin, watching events and the signal watcher. */
            crossbeam::select! {
                recv(receiver) -> r => {
                    match r {
                         Ok(ThreadEvent::Pulse) | Ok(ThreadEvent::UIEvent(UIEvent::Timer(_))) => {},
                        _ => {debug!(&r);}
                    }
                    match r.unwrap() {
                        ThreadEvent::Input((Key::Ctrl('z'), _)) if state.mode != UIMode::Embed => {
                            state.switch_to_main_screen();
                            //_thread_handler.join().expect("Couldn't join on the associated thread");
                            //let self_pid = nix::unistd::Pid::this();
                            //nix::sys::signal::kill(self_pid, nix::sys::signal::Signal::SIGSTOP).unwrap();
                            state.switch_to_alternate_screen();
                            // BUG: thread sends input event after one received key
                            state.update_size();
                            state.render();
                            state.redraw();
                        },
                        ThreadEvent::Input(raw_input @ (Key::Ctrl('l'), _)) => {
                            /* Manual screen redraw */
                            state.update_size();
                            state.render();
                            state.redraw();
                            if state.mode == UIMode::Embed {
                                state.rcv_event(UIEvent::EmbedInput(raw_input));
                                state.redraw();
                            }
                        },
                        ThreadEvent::Input((k, r)) => {
                            match state.mode {
                                UIMode::Normal => {
                                    match k {
                                        Key::Char('q') | Key::Char('Q') => {
                                            if state.can_quit_cleanly() {
                                                drop(state);
                                                break 'main;
                                            } else {
                                                state.redraw();
                                            }
                                        },
                                        Key::Char(' ') => {
                                            state.mode = UIMode::Execute;
                                            state.rcv_event(UIEvent::ChangeMode(UIMode::Execute));
                                            state.redraw();
                                        }
                                        key  => {
                                            state.rcv_event(UIEvent::Input(key));
                                            state.redraw();
                                        },
                                    }
                                },
                                UIMode::Insert => {
                                    match k {
                                        Key::Char('\n') | Key::Esc => {
                                            state.mode = UIMode::Normal;
                                            state.rcv_event(UIEvent::ChangeMode(UIMode::Normal));
                                            state.redraw();
                                        },
                                        k => {
                                            state.rcv_event(UIEvent::InsertInput(k));
                                            state.redraw();
                                        },
                                    }
                                }
                                UIMode::Execute => {
                                    match k {
                                        Key::Char('\n') | Key::Esc => {
                                            state.mode = UIMode::Normal;
                                            state.rcv_event(UIEvent::ChangeMode(UIMode::Normal));
                                            state.redraw();
                                        },
                                        k => {
                                            state.rcv_event(UIEvent::ExInput(k));
                                            state.redraw();
                                        },
                                    }
                                },
                                UIMode::Embed => {
                                    state.rcv_event(UIEvent::EmbedInput((k,r)));
                                    state.redraw();
                                },
                                UIMode::Fork => {
                                    break 'inner; // `goto` 'reap loop, and wait on child.
                                },
                            }
                        },
                        ThreadEvent::RefreshMailbox(event) => {
                            state.refresh_event(*event);
                            state.redraw();
                        },
                        ThreadEvent::UIEvent(UIEvent::ChangeMode(f)) => {
                            state.mode = f;
                            if f == UIMode::Fork {
                                break 'inner; // `goto` 'reap loop, and wait on child.
                            }
                        }
                        ThreadEvent::UIEvent(e) => {
                            state.rcv_event(e);
                            state.redraw();
                        },
                        ThreadEvent::Pulse => {
                            state.check_accounts();
                            state.redraw();
                        },
                        ThreadEvent::JobFinished(id) => {
                            debug!("Job finished {}", id);
                            for account in state.context.accounts.iter_mut() {
                                if account.process_event(&id) {
                                    break;
                                }
                            }
                            //state.new_thread(id, name);
                        },
                    }
                },
            }
        } // end of 'inner

        'reap: loop {
            match state.try_wait_on_child() {
                Some(true) => {
                    state.restore_input();
                    state.switch_to_alternate_screen();
                }
                Some(false) => {
                    use std::{thread, time};
                    let ten_millis = time::Duration::from_millis(1500);
                    thread::sleep(ten_millis);

                    continue 'reap;
                }
                None => {
                    state.mode = UIMode::Normal;
                    state.render();
                    break 'reap;
                }
            }
        }
    }
    Ok(())
}
