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>,
    bool,
    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_is_dirty", callback)?
        .build_threadsafe_function()
        .build()
}

fn callback(function_call_context: FunctionCallContext) -> Result<bool, 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 document = text_editor.get_document()?;

    document.get_is_dirty()
}