/* portal.rs
 *
 * Copyright 2026 Christian Kruse
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

use std::path::Path;

use gettextrs::gettext;
use relm4::gtk::gio;
use relm4::gtk::prelude::*;

pub fn fallback_notice() -> String {
    gettext(
        "Your system's xdg-desktop-portal doesn't support folder selection, so this simpler text input is shown \
         instead. Please enter or paste the absolute path manually.",
    )
}

pub fn is_flatpak() -> bool {
    Path::new("/.flatpak-info").exists()
}

/*
 * this function checks if the portal supports folder selection, which is required for several dialogs. It has
 * been added with xdg-desktop-portal 1.7.1, but some distributions (e.g. Debian) are still shipping older versions.
 * In that case, we need to fall back to a modal with a textbox.
 *
 * use `GITTE_FORCE_PORTAL_FALLBACK=1` to enforce the fallback
 */
pub fn folder_select_supported() -> bool {
    if std::env::var("GITTE_FORCE_PORTAL_FALLBACK").is_ok_and(|v| v == "1") {
        tracing::info!("portal: folder-select fallback forced via GITTE_FORCE_PORTAL_FALLBACK");
        return false;
    }

    if !is_flatpak() {
        return true;
    }

    let version = portal_filechooser_version();
    tracing::info!("portal: FileChooser interface version is {version:?}");

    version.is_some_and(|v| v >= 3)
}

fn portal_filechooser_version() -> Option<u32> {
    let proxy = gio::DBusProxy::for_bus_sync(
        gio::BusType::Session,
        gio::DBusProxyFlags::NONE,
        None,
        "org.freedesktop.portal.Desktop",
        "/org/freedesktop/portal/desktop",
        "org.freedesktop.portal.FileChooser",
        gio::Cancellable::NONE,
    )
    .ok()?;

    proxy.cached_property("version")?.get::<u32>()
}
