// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright © 2024 Mike Robeson [dijksterhuis]

use std::path::Path;

use ot_tools_io::identifiers::BankId;
use ot_tools_io::identifiers::SavedState;
use ot_tools_io::BankFile;
use ot_tools_io::IsDefault;

use crate::projects::DataItem;
use crate::projects::R;

/// A [`DataItem`] aliased type for an `ot_tools_io::BankFile`, aiming to make
/// handling bank files easier.
pub type BankDataFile = DataItem<BankFile>;

impl AsRef<BankDataFile> for BankDataFile {
    fn as_ref(&self) -> &BankDataFile {
        self
    }
}

impl BankDataFile {
    /// Creates a new [`BankDataFile`] ready to call `write()` and save the data
    /// to the filesystem.
    pub fn create(dirpath: &Path, id: &BankId) -> Self {
        let path = dirpath
            .join(id.file_stem(&SavedState::Working))
            .to_path_buf();
        let data = BankFile::default();
        Self::new(path, data)
    }

    /// Loads a new [`BankDataFile`] from filesystem.
    pub fn load(dirpath: &Path, id: &BankId, state: &SavedState) -> R<Self> {
        let path = dirpath.join(id.file_stem(state)).to_path_buf();
        BankDataFile::read(path)
    }

    /// Essentially a `x.clone()` under the hood, but allows modifying where the
    /// file will be written to in advance.
    pub fn to_new(&self, new_dirpath: &Path, id: &BankId, state: &SavedState) -> R<Self> {
        let mut new = self.clone();
        new.source = new_dirpath.join(id.file_stem(state)).to_path_buf();
        Ok(new)
    }

    /// Wrapper for the `is_default()` method from the `ot_tools_io::IsDefault`
    /// trait.
    pub fn is_default(&self) -> R<bool> {
        Ok(self.data.is_default())
    }
}
