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

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 main_qml_path: PathBuf = current_dir.join("qml/main.qml");
    let main_qml_path = match main_qml_path.canonicalize() {
        Ok(v) => v,
        Err(err) => {
            eprintln!(
                "failed to resolve qml/main.qml from {}: {err}",
                main_qml_path.display()
            );
            return;
        }
    };

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

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

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

    if let Some(app_ref) = app.as_mut() {
        app_ref.exec();
    } else {
        eprintln!("failed to create QGuiApplication");
    }
}
