pub use rfd::*;

#[cfg(not(target_os = "linux"))]
macro_rules! run_dialog {
  ($e:expr, $h: ident) => {{
    std::thread::spawn(move || {
      let response = $e;
      $h(response);
    });
  }};
}

#[cfg(target_os = "linux")]
macro_rules! run_dialog {
  ($e:expr, $h: ident) => {{
    std::thread::spawn(move || {
      let context = glib::MainContext::default();
      context.invoke_with_priority(glib::PRIORITY_HIGH, move || {
        let response = $e;
        $h(response);
      });
    });
  }};
}


/// # 运行dialog
/// ```rust
/// use e_utils::dialog::*;
/// use std::sync::mpsc::channel;
/// fn main() {
///   let (sx, rx) = channel();
///   dialog(
///     "测试",
///     "通知",
///     MessageButtons::Ok,
///     MessageLevel::Error,
///     move |_x| {
///       sx.send(true).unwrap();
///     },
///   );
///   rx.recv().unwrap();
/// }
/// ```
#[allow(unused_variables)]
pub fn dialog<F: FnOnce(MessageDialogResult) + Send + 'static>(
  title: impl AsRef<str>,
  message: impl AsRef<str>,
  buttons: MessageButtons,
  level: MessageLevel,
  f: F,
) {
  let title = title.as_ref().to_string();
  let message = message.as_ref().to_string();
  #[allow(unused_mut)]
  let mut builder = MessageDialog::new()
    .set_title(&title)
    .set_description(&message)
    .set_buttons(buttons)
    .set_level(level.into());

  run_dialog!(builder.show(), f)
}

/// # 运行dialog
/// ```rust
/// use e_utils::dialog::*;
/// use e_utils::Result;
/// fn main() -> Result<()> {
///   dialog_block(
///     "测试",
///     "通知",
///     MessageButtons::Ok,
///     MessageLevel::Error,
///     |_x| {},
///   );
///   Ok(())
/// }
///```
#[allow(unused_variables)]
pub fn dialog_block<F: FnOnce(MessageDialogResult) + Send + 'static>(
  title: impl AsRef<str>,
  message: impl AsRef<str>,
  buttons: MessageButtons,
  level: MessageLevel,
  f: F,
) {
  let title = title.as_ref().to_string();
  let message = message.as_ref().to_string();
  #[allow(unused_mut)]
  let mut builder = MessageDialog::new()
    .set_title(&title)
    .set_description(&message)
    .set_buttons(buttons)
    .set_level(level.into());
  f(builder.show())
}
/// # 错误dialog
#[allow(unused_variables)]
pub fn dialog_err(title: impl AsRef<str>, message: impl AsRef<str>) {
  let msg = message.as_ref();
  dialog(
    title.as_ref(),
    msg,
    MessageButtons::Ok,
    MessageLevel::Error,
    |_|{},
  );
}
/// # 错误dialog
#[allow(unused_variables)]
pub fn dialog_err_block(title: impl AsRef<str>, message: impl AsRef<str>) {
  let msg = message.as_ref();
  dialog_block(
    title.as_ref(),
    msg,
    MessageButtons::Ok,
    MessageLevel::Error,
    |_|{},
  );
}
