mod db;
mod parser;
mod commands;

use commands::DbState;
use std::sync::Mutex;
use tauri::Manager;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .setup(|app| {
            let conn = db::open().expect("Failed to open database");
            db::migrate(&conn).expect("Failed to migrate database");
            app.manage(DbState(Mutex::new(conn)));

            #[cfg(target_os = "linux")]
            {
                use gtk::prelude::*;
                use webkit2gtk::WebViewExt;

                let window = app.get_webview_window("main").expect("no main window");
                window.eval(r#"(function(){
                    var s=document.createElement('style');
                    s.textContent='*:not(.with-scrollbar)::-webkit-scrollbar{display:none!important;width:0!important;height:0!important}*:not(.with-scrollbar){scrollbar-width:none!important}';
                    var apply=function(){if(document.head)document.head.appendChild(s)};
                    if(document.head)apply();else document.addEventListener('DOMContentLoaded',apply);
                })();"#).ok();
                window.with_webview(|wv| {
                    let webkit_view = wv.inner();
                    if let Some(parent) = webkit_view.parent() {
                        if let Ok(sw) = parent.downcast::<gtk::ScrolledWindow>() {
                            sw.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Never);
                        }
                    }
                }).ok();
            }

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            commands::get_profiles,
            commands::create_profile,
            commands::delete_profile,
            commands::get_completed_quests,
            commands::toggle_quest,
            commands::get_guides_list,
            commands::get_guide,
            commands::sync_guides,
            commands::get_tabs_list,
            commands::sync_single_guide,
            commands::has_guides,
            commands::get_setting,
            commands::set_setting,
            commands::set_always_on_top,
            commands::fetch_quest_detail,
            commands::get_completed_steps,
            commands::toggle_quest_step,
            commands::get_resource_inventory,
            commands::set_resource_quantity,
            commands::open_image_viewer,
            commands::get_cached_previews,
            commands::fetch_guide_previews,
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
