// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::path::PathBuf;

use anyhow::{Context, Result};

fn get_runtime_path(name: &'static str) -> Result<PathBuf> {
    let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?;
    xdg_dirs
        .place_runtime_file(name)
        .with_context(|| format!("Failed to place runtime file: '{}'", name))
}
fn get_data_path(name: &'static str) -> Result<PathBuf> {
    let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?;
    xdg_dirs
        .place_data_file(name)
        .with_context(|| format!("Failed to place data file: '{}'", name))
}
fn get_config_path(name: &'static str) -> Result<PathBuf> {
    let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?;
    xdg_dirs
        .place_config_file(name)
        .with_context(|| format!("Failed to place config file: '{}'", name))
}

pub(super) fn create_path(path: PathBuf) -> Result<PathBuf> {
    if !path.exists() {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(&parent)
                .with_context(|| format!("Failed to create the '{}' directory", path.display()))?
        }
    }

    Ok(path)
}

pub const PREFIX: &str = "yt";

pub mod select {
    pub fn playback_speed() -> f64 {
        2.7
    }
    pub fn subtitle_langs() -> &'static str {
        ""
    }
}

pub mod watch {
    pub fn local_comments_length() -> i64 {
        1000
    }
}

pub mod update {
    pub fn max_backlog() -> i64 {
        20
    }
}

pub mod paths {
    use std::{env::temp_dir, path::PathBuf};

    use anyhow::Result;

    use super::{create_path, get_config_path, get_data_path, get_runtime_path, PREFIX};

    // We download to the temp dir to avoid taxing the disk
    pub fn download_dir() -> Result<PathBuf> {
        let temp_dir = temp_dir();

        create_path(temp_dir.join(PREFIX))
    }
    pub fn mpv_config_path() -> Result<PathBuf> {
        get_config_path("mpv.conf")
    }
    pub fn mpv_input_path() -> Result<PathBuf> {
        get_config_path("mpv.input.conf")
    }
    pub fn database_path() -> Result<PathBuf> {
        get_data_path("videos.sqlite")
    }
    pub fn config_path() -> Result<PathBuf> {
        get_config_path("config.toml")
    }
    pub fn last_selection_path() -> Result<PathBuf> {
        get_runtime_path("selected.yts")
    }
}

pub mod download {
    pub fn max_cache_size() -> &'static str {
        "3 GiB"
    }
}