use std::path::Path;

use lunar_lib::database::{DatabaseEntry, DatabaseError, DbHandle};

use crate::{database::LibraryDb, library::track::Track};

impl Track {
    pub fn db_find_by_title(name: impl AsRef<str>) -> Result<Vec<Self>, DatabaseError> {
        let name = name.as_ref();

        let db = DbHandle::<LibraryDb>::open()?;
        let mut tracks = Self::db_get_all(&db)?;
        tracks.retain(|t| t.metadata.title.as_deref() == Some(name));

        Ok(tracks)
    }

    pub fn db_find_by_path(path: impl AsRef<Path>) -> Result<Option<Self>, DatabaseError> {
        let path = path.as_ref();

        let db = DbHandle::<LibraryDb>::open()?;
        let tracks = Self::db_get_all(&db)?;
        let track = tracks.into_iter().find(|t| t.container.path() == path);

        Ok(track)
    }
}
