use std::path;

use crate::error::AppResult;
use crate::history::create_dirlist_with_history;
use crate::types::keymap::AppKeyMapping;
use crate::types::state::AppState;
use crate::ui::AppBackend;

use super::command_line;

/// Renames `src` to `dest` on disk (failing if `dest` already exists) and refreshes the current
/// directory's cached listing.
pub fn _rename_file(
    app_state: &mut AppState,
    src: &path::Path,
    dest: &path::Path,
) -> std::io::Result<()> {
    let new_path = dest;
    if new_path.exists() {
        let err = std::io::Error::new(std::io::ErrorKind::AlreadyExists, "Filename already exists");
        return Err(err);
    }
    std::fs::rename(src, dest)?;

    let curr_tab = app_state.state.tab_state_ref().curr_tab_ref();

    let path = curr_tab
        .curr_list_ref()
        .map(|lst| lst.file_path().to_path_buf());

    if let Some(path) = path {
        let new_dirlist = {
            let display_options = &app_state.config.display_options;
            let tab_options = app_state.state.tab_state_ref().curr_tab_ref().option_ref();
            let history = app_state.state.tab_state_ref().curr_tab_ref().history_ref();
            create_dirlist_with_history(history, path.as_path(), display_options, tab_options)?
        };
        let history = app_state.state.tab_state_mut().curr_tab_mut().history_mut();
        history.insert(path, new_dirlist);
    }
    Ok(())
}

/// Implements `rename`: renames the current entry to `dest`.
pub fn rename_file(app_state: &mut AppState, dest: &path::Path) -> AppResult {
    let path: Option<path::PathBuf> = app_state
        .state
        .tab_state_ref()
        .curr_tab_ref()
        .curr_list_ref()
        .and_then(|s| s.curr_entry_ref())
        .map(|s| s.file_path().to_path_buf());

    if let Some(path) = path {
        _rename_file(app_state, path.as_path(), dest)?;
    }
    Ok(())
}

/// Returns the file name of the entry under the cursor, if any.
fn _get_current_file_name(app_state: &mut AppState) -> Option<String> {
    app_state
        .state
        .tab_state_ref()
        .curr_tab_ref()
        .curr_list_ref()
        .and_then(|list| list.curr_entry_ref().map(|s| s.file_name().to_string()))
}

/// Implements `rename_append`: opens the command line pre-filled with `rename <current name>`,
/// cursor at the end, for appending to the file name.
pub fn rename_file_append(
    app_state: &mut AppState,
    backend: &mut AppBackend,
    keymap_t: &AppKeyMapping,
) -> AppResult {
    if let Some(file_name) = _get_current_file_name(app_state) {
        let (prefix, suffix) = (format!("rename {}", file_name), "".to_string());
        command_line::read_and_execute(app_state, backend, keymap_t, &prefix, &suffix)?;
    }
    Ok(())
}

/// Implements `rename_append_base`: opens the command line with the cursor placed right after
/// the file's base name (before its extension), for appending before the extension.
pub fn rename_file_append_base(
    app_state: &mut AppState,
    backend: &mut AppBackend,
    keymap_t: &AppKeyMapping,
) -> AppResult {
    if let Some(file_name) = _get_current_file_name(app_state) {
        let (prefix, suffix): (String, String) = match file_name.rfind('.') {
            Some(ext) => (
                format!("rename {}", &file_name[0..ext]),
                file_name[ext..].to_string(),
            ),
            None => (format!("rename {}", file_name), "".to_string()),
        };
        command_line::read_and_execute(app_state, backend, keymap_t, &prefix, &suffix)?;
    }
    Ok(())
}

/// Implements `rename_prepend`: opens the command line with the cursor before the current file
/// name, for prepending text.
pub fn rename_file_prepend(
    app_state: &mut AppState,
    backend: &mut AppBackend,
    keymap_t: &AppKeyMapping,
) -> AppResult {
    if let Some(file_name) = _get_current_file_name(app_state) {
        let (prefix, suffix) = ("rename ".to_string(), file_name);
        command_line::read_and_execute(app_state, backend, keymap_t, &prefix, &suffix)?;
    }
    Ok(())
}

/// Implements `rename_keep_ext`: opens the command line with the base name cleared but the
/// extension preserved as suffix text.
pub fn rename_file_keep_ext(
    app_state: &mut AppState,
    backend: &mut AppBackend,
    keymap_t: &AppKeyMapping,
) -> AppResult {
    if let Some(file_name) = _get_current_file_name(app_state) {
        let (prefix, suffix): (String, String) = match file_name.rfind('.') {
            Some(ext) => ("rename ".to_string(), file_name[ext..].to_string()),
            None => ("rename ".to_string(), "".to_string()),
        };
        command_line::read_and_execute(app_state, backend, keymap_t, &prefix, &suffix)?;
    }
    Ok(())
}
