// Fragments - secret_store.rs
// Copyright (C) 2022-2024  Felix Häcker <haeckerfelix@gnome.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::collections::HashMap;
use std::sync::OnceLock;

use transmission_gobject::TrAuthentication;

use crate::backend::FrgConnection;

static KEYRING: OnceLock<oo7::Keyring> = OnceLock::new();

pub async fn open_keyring() -> oo7::Result<()> {
    let keyring = oo7::Keyring::new().await?;

    if KEYRING.set(keyring).is_err() {
        debug!("Keyring was already set");
    }

    Ok(())
}

pub async fn store(conn: &FrgConnection, auth: &TrAuthentication) -> Result<(), oo7::Error> {
    remove(conn).await?;

    let username = auth.username();
    let uuid = conn.uuid();

    let attributes: HashMap<&str, &str> =
        [("username", username.as_str()), ("uuid", uuid.as_str())]
            .iter()
            .cloned()
            .collect();

    let title = format!("Fragments ({})", conn.title());

    KEYRING.get().unwrap().unlock().await?;
    KEYRING
        .get()
        .unwrap()
        .create_item(&title, &attributes, auth.password().as_bytes(), true)
        .await?;

    Ok(())
}

pub async fn get(conn: &FrgConnection) -> Result<Option<TrAuthentication>, oo7::Error> {
    let uuid = conn.uuid();
    let attributes: HashMap<&str, &str> = [("uuid", uuid.as_str())].iter().cloned().collect();

    KEYRING.get().unwrap().unlock().await?;
    let items = KEYRING.get().unwrap().search_items(&attributes).await?;

    if let Some(item) = items.first() {
        let attributes = item.attributes().await?;

        let username = attributes
            .get("username")
            .expect("Couldn't get secretservice username attribute");

        let password = String::from_utf8(item.secret().await?.to_vec())
            .expect("Couldn't parse secretservice secret");

        Ok(Some(TrAuthentication::new(username, &password)))
    } else {
        Ok(None)
    }
}

pub async fn remove(conn: &FrgConnection) -> Result<(), oo7::Error> {
    let uuid = conn.uuid();
    let attributes: HashMap<&str, &str> = [("uuid", uuid.as_str())].iter().cloned().collect();

    KEYRING.get().unwrap().unlock().await?;
    KEYRING.get().unwrap().delete(&attributes).await?;

    Ok(())
}
