use iri_string::types::UriAbsoluteString;

use crate::event_loop::ExtensionState;
use crate::event_loop::js_function::Functions;

#[tracing::instrument(skip(extension_state, js_functions))]
pub async fn handle(
    uri: UriAbsoluteString,
    extension_state: &mut ExtensionState,
    js_functions: &Functions,
) {
    let Some((_repository_path, relative_path, repository)) =
        extension_state.get_repository_mut(&uri)
    else {
        tracing::info!(message = "Ignoring filesystem changes");
        return;
    };

    match repository
        .repository
        .update_path_state(relative_path.to_path_buf())
    {
        Ok(()) => tracing::debug!(message = "Updated path state"),
        Err(error) => {
            tracing::error!(
                message = "Failed to update path states",
                ?relative_path,
                ?error
            );
            return;
        }
    }

    match js_functions
        .fire_decoration_change_event(uri, &extension_state.decoration_change_event_emitter)
        .await
    {
        Ok(()) => {
            tracing::debug!(message = "Fired onDidChangeFileDecorations");
        }
        Err(error) => {
            tracing::warn!(
                message = "Failed to fire onDidChangeFileDecorations",
                ?error
            );
        }
    }
}