use std::rc::Rc;

use napi::bindgen_prelude::{External, FunctionCallContext};
use napi::threadsafe_function::ThreadsafeFunction;

use crate::vscode_sys;

pub struct Arguments {
    pub text_editor_reference: Rc<vscode_sys::reference::TextEditorRef>,
}

pub type Prototype = ThreadsafeFunction<
    External<Arguments>,
    Vec<(u32, u32)>,
    External<Arguments>,
    napi::Status,
    false,
    false,
    0,
>;

pub fn build(env: &napi::Env) -> Result<Prototype, napi::Error> {
    env.create_function_from_closure("get_text_editor_selections", callback)?
        .build_threadsafe_function()
        .build()
}

fn callback(function_call_context: FunctionCallContext) -> Result<Vec<(u32, u32)>, napi::Error> {
    let (external,): (&External<Arguments>,) = function_call_context.args()?;
    let Arguments {
        text_editor_reference,
    } = &**external;

    let text_editor = text_editor_reference.get_inner(function_call_context.env)?;
    let editor_selections = text_editor.get_selections()?;
    let mut selections = Vec::with_capacity(editor_selections.len());

    for editor_selection in text_editor.get_selections()? {
        let start_line = editor_selection.get_start()?.get_line()?;
        let end_line = editor_selection.get_end()?.get_line()?;

        selections.push((start_line, end_line));
    }

    Ok(selections)
}