// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

#[cfg(all(target_arch = "wasm32", feature = "preview-external"))]
mod wasm;
#[cfg(all(target_arch = "wasm32", feature = "preview-external"))]
pub use wasm::*;

#[cfg(all(not(target_arch = "wasm32"), feature = "preview-builtin"))]
pub mod native;
#[cfg(all(not(target_arch = "wasm32"), feature = "preview-builtin"))]
pub use native::*;

#[cfg(all(not(target_arch = "wasm32"), feature = "preview-remote"))]
pub mod remote;

use crate::preview;
use i_slint_live_preview::protocol::LspToPreviewMessage;

pub fn lsp_to_preview(message: LspToPreviewMessage) {
    use LspToPreviewMessage as M;
    match message {
        M::InvalidateContents { url } => preview::invalidate_contents(&url),
        M::ForgetFile { url } => preview::delete_document(&url),
        M::SetContents { url, contents } => {
            if let Ok(contents) = String::from_utf8(contents) {
                preview::set_contents(&url, contents);
            }
        }
        M::SetConfiguration { config } => {
            preview::config_changed(config);
        }
        M::ShowPreview(pc) => {
            tracing::debug!(
                "Preview: ShowPreview for url={}, component={:?}",
                pc.url,
                pc.component
            );
            preview::load_preview(pc, preview::LoadBehavior::BringWindowToFront);
        }
        M::HighlightFromEditor { url, offset } => {
            preview::highlight(url, offset.into());
        }
        M::RemoteConnectionState { state, target, error } => {
            preview::set_remote_connection_state(state, target, error);
        }
        M::Quit => {
            tracing::debug!("Preview: Quit requested");
            #[cfg(not(target_arch = "wasm32"))]
            let _ = slint::quit_event_loop();
        }
        M::Ping => {
            // Keepalive for the remote-preview WebSocket; local previews never see it.
        }
    }
}
