/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use anyhow::Result;
use log::debug;
use rayon::{current_num_threads, current_thread_index};
use serde::Serialize;
use tokio::sync::RwLock;

pub static IMPORT_ERRORS: RwLock<Vec<String>> = RwLock::const_new(Vec::new());
pub static IMPORT_PROGRESS: RwLock<Option<ImportProgress>> = RwLock::const_new(None);

#[derive(Debug, Serialize, Clone)]
pub struct ImportProgress {
    pub total_items: usize,
    pub finished_items: usize,
    pub tasks: Vec<String>,
}

pub(crate) fn start_import() {
    *IMPORT_ERRORS.blocking_write() = Vec::new();
    *IMPORT_PROGRESS.blocking_write() = Some(ImportProgress {
        total_items: 0,
        finished_items: 0,
        tasks: vec!["idle".to_string(); current_num_threads()],
    });
}
pub(crate) fn end_import() {
    *IMPORT_PROGRESS.blocking_write() = None;
}

pub(crate) fn set_task(task: String) {
    let thread = current_thread_index().unwrap_or(0);
    debug!("T#{thread:<3}| {task}");
    if let Some(p) = IMPORT_PROGRESS.blocking_write().as_mut() {
        p.tasks[thread] = task
    }
}

pub(crate) fn catch<T>(res: Result<T>) -> Option<T> {
    match res {
        Ok(res) => Some(res),
        Err(e) => {
            IMPORT_ERRORS.blocking_write().push(format!("{e:#}"));
            None
        }
    }
}
