#![allow(non_snake_case)]

mod components;
mod err;
mod util;

#[cfg(feature = "server")]
pub use err::Error;

use dioxus::prelude::*;
use tracing::Level;

// Use routes
use components::admin::members::migration::Migration;
use components::admin::members::Members;
use components::agenda::Agenda;
use components::home::Home;
use components::layout::Global;
use components::news::News;
use components::settings::Settings;

#[derive(Clone, Routable, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Route {
    #[layout(Global)]
    #[route("/")]
    Home {},
    #[route("/agenda")]
    Agenda {},
    #[route("/news")]
    News {},
    #[route("/settings")]
    Settings {},
    #[route("/admin/members")]
    Members {},
    #[route("/admin/members/migration")]
    Migration {},
}

const _TAILWIND_URL: &str = manganis::mg!(file("assets/tailwind.css"));

fn main() {
    // Init logger
    dioxus_logger::init(Level::INFO).expect("failed to init logger");

    #[cfg(feature = "server")]
    {
        use axum::routing::*;

        // Spawn main tokio runtime
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(async move {
                // Initialize surrealdb connection
                util::surrealdb::initialize()
                    .await
                    .expect("Error while initializing surrealdb");

                // Create axum app
                let app = Router::new()
                    .serve_dioxus_application(ServeConfig::builder().build(), || {
                        VirtualDom::new(App)
                    })
                    .await;

                // Run axum app
                let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
                let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();

                axum::serve(listener, app.into_make_service())
                    .await
                    .unwrap();
            });
    }

    launch(App);
}

fn App() -> Element {
    rsx! {
        div {
            class: "h-screen flex flex-col",
            Router::<Route> {}
        }
    }
}
