#![cfg_attr(
  all(not(debug_assertions), target_os = "windows"),
  windows_subsystem = "windows"
)]

use tauri::Manager; 
// use tauri::{App, Builder}; 
use serde::{Deserialize, Serialize};
use serde_json::{Result, Value, json};

#[derive(Serialize, Deserialize, Debug)]
struct ZEvent {
    sender: String,
    data: Option<String>
}

impl ZEvent {
    fn default() -> Self {
      ZEvent { sender: String::default(), data: None }
    } 
}

#[tauri::command]
fn greet(name: &str) -> String {
   format!("Hello, {}!", name)
}

fn main() {

  // prepare() checks if it's a single instance and tries to send the args otherwise.
  // It should always be the first line in your main function (with the exception of loggers or similar)
  tauri_plugin_deep_link::prepare("com.zlmix.zmusic");

  tauri::Builder::default()
    .setup(move |app| {

      // If you need macOS support this must be called in .setup() !
      // Otherwise this could be called right after prepare() but then you don't have access to tauri APIs
      let handle = app.handle();
      tauri_plugin_deep_link::register(
        "zm-scheme",
        move |request| {
          dbg!(&request);
          handle.emit_all("zm-scheme-request-received", request).unwrap();
        },
      )
      .unwrap(/* If listening to the scheme is optional for your app, you don't want to unwrap here. */);


    // let sp = app.get_window("splashscreen").unwrap();
    let main = app.get_window("main").unwrap();

    // sp.show().unwrap();

    app.listen_global("dom-loaded", move |event| {
      // let data = event.payload();

      let v = json!(
        {
          "sender": "haah",
          "data": {
            "id": 234421,
            "message": "测试消息"
          }
        }
      );

      if let Some(data) = event.payload() {
        
        let jdata: Value = serde_json::from_str(data).unwrap();
        let ev: Option<ZEvent> = serde_json::from_str(data).ok();
        // match serde_json::from_str(data) {
        //   Ok(ev) => {}
        //   _ => {}
        // } 
        println!("jdata is {}, ev is {:?}", jdata, ev);
        // return;

        // match ev.sender.as_str() {
        //   "discover/recommend" => {
        //     main.show().unwrap();
        //     println!("main is ready to show");
        //   }
        //   _ => {}
        // }

        if let Some(data) = jdata["data"].as_object() {
          
        }

        if let Some(sender) = jdata["sender"].as_str() {
          match sender {
              "discover/recommend" => {
                main.show().unwrap();
                println!("main is ready to show");
              }
              _ => {}
          }
        }
        
      }
    });

    Ok(())
  })
    // .invoke_handler(tauri::generate_handler![register_protocol])
    .invoke_handler(tauri::generate_handler!
      [
        // register_protocol,
        greet,
      ])
    .run(tauri::generate_context!())
    .expect("error while running tauri application");


    // let app = App::new()
    // .protocols(&[
    //     "my-custom-protocol",
    //     "http://www.example.com/my-custom-protocol",
    // ])
    // .run();

}
