mod app;
mod data;
mod utils;
mod widgets;

use adw::prelude::*;
use app::KrApp;
use gettextrs::*;
use gtk::{gio, glib};
use gvdb_macros::include_gresource_from_dir;
use tracing_subscriber::prelude::*;

const APP_ID: &str = if let Some(app_id) = option_env!("APPLICATION_ID") {
    app_id
} else {
    "app.drey.KeyReck"
};

const LOCALEDIR: &str = if let Some(app_id) = option_env!("LOCALEDIR") {
    app_id
} else {
    "/usr/share/locale"
};

static GRESOURCE_BYTES: &[u8] = include_gresource_from_dir!("/app/drey/KeyRack", "data/resources");

thread_local!(
    static APPLICATION: KrApp = KrApp::new();
);

pub fn app() -> KrApp {
    APPLICATION.with(|x| x.clone())
}

fn main() {
    // Follow G_MESSAGES_DEBUG env variable
    let default_level =
        if !glib::log_writer_default_would_drop(glib::LogLevel::Debug, Some("key-rack")) {
            tracing_subscriber::filter::LevelFilter::DEBUG
        } else {
            tracing_subscriber::filter::LevelFilter::WARN
        };

    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::builder()
                .with_default_directive(default_level.into())
                .from_env_lossy(),
        )
        .with(
            tracing_subscriber::fmt::Layer::default()
                .compact()
                .with_line_number(true)
                .with_writer(std::io::stderr),
        )
        .init();

    tracing::debug!("Logger initialized");

    setlocale(LocaleCategory::LcAll, "");
    bindtextdomain("key-rack", crate::LOCALEDIR).unwrap();
    textdomain("key-rack").unwrap();

    gio::resources_register(
        &gio::Resource::from_data(&glib::Bytes::from_static(GRESOURCE_BYTES)).unwrap(),
    );

    app().run();
}
