use std::cell::RefCell;
use std::rc::Rc;

use crate::app_state::AppState;
use crate::dialog_support::show_error_dialog_with_parent;
use crate::file_ops::{
    launch_default_browser_for_path, launch_default_browser_for_url, portable_path,
};
use crate::review_ui::ReviewUi;

pub(crate) fn open_user_guide_from_menu(ui: &ReviewUi, state: &Rc<RefCell<AppState>>) {
    let localizer = state.borrow().localizer;
    let guide_path = portable_path(localizer.user_guide_html_path());
    if !guide_path.exists() {
        show_error_dialog_with_parent(
            &ui.frame,
            localizer.could_not_open_user_guide_caption(),
            &localizer.user_guide_missing_message(&guide_path),
        );
        return;
    }

    if launch_default_browser_for_path(&guide_path).is_err() {
        show_error_dialog_with_parent(
            &ui.frame,
            localizer.could_not_open_user_guide_caption(),
            &localizer.could_not_open_user_guide_message(&guide_path),
        );
    }
}

pub(crate) fn open_bug_report_from_menu(ui: &ReviewUi, state: &Rc<RefCell<AppState>>) {
    let localizer = state.borrow().localizer;
    let url = localizer.report_bug_url();

    if launch_default_browser_for_url(url).is_err() {
        show_error_dialog_with_parent(
            &ui.frame,
            localizer.could_not_open_bug_report_caption(),
            &localizer.could_not_open_bug_report_message(url),
        );
    }
}

pub(crate) fn open_project_wiki_from_menu(ui: &ReviewUi, state: &Rc<RefCell<AppState>>) {
    let localizer = state.borrow().localizer;
    let url = localizer.project_wiki_url();

    if launch_default_browser_for_url(url).is_err() {
        show_error_dialog_with_parent(
            &ui.frame,
            localizer.could_not_open_project_wiki_caption(),
            &localizer.could_not_open_project_wiki_message(url),
        );
    }
}
