// file: poc-qt/poc005/src/main.rs

mod bridge;

use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QString, QUrl};
use std::env;
use std::path::PathBuf;

fn main() {
    let mut app = QGuiApplication::new();
    let mut engine = QQmlApplicationEngine::new();

    let current_dir = match env::current_dir() {
        Ok(v) => v,
        Err(err) => {
            eprintln!("failed to get current_dir: {err}");
            return;
        }
    };

    let qml_path: PathBuf = current_dir.join("qml/main.qml");
    let qml_path = match qml_path.canonicalize() {
        Ok(v) => v,
        Err(err) => {
            eprintln!("failed to resolve qml/main.qml: {err}");
            return;
        }
    };

    let qml_path_str = match qml_path.to_str() {
        Some(v) => v.to_string(),
        None => {
            eprintln!("qml path is not valid UTF-8: {}", qml_path.display());
            return;
        }
    };

    println!("loading qml from: {}", qml_path_str);

    if let Some(engine_ref) = engine.as_mut() {
        let url = QUrl::from_local_file(&QString::from(qml_path_str));
        engine_ref.load(&url);
    } else {
        eprintln!("failed to create QQmlApplicationEngine");
        return;
    }

    if let Some(app_ref) = app.as_mut() {
        app_ref.exec();
    }
}
