use std::{fmt, time::Duration};

use lofty::tag::items::Timestamp;

#[derive(Debug, Clone, Default)]
pub struct Metadata {
    pub title: Option<String>,
    pub artist: Option<String>,
    pub album: Option<String>,
    pub time_stamp: Option<Timestamp>,
    pub genre: Option<String>,
    pub cover: Option<Vec<u8>>,
    pub duration: Duration,
    pub sample_rate: Option<u32>,
    pub channels: Option<u8>,
    pub has_tag: bool,
}

#[derive(Debug)]
pub enum MetadataError {
    ReadError,
    NoTag,
}

impl fmt::Display for Metadata {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.title.as_deref().unwrap_or(""))?;
        write!(f, "{}", self.artist.as_deref().unwrap_or(""))?;
        write!(f, "{}", self.album.as_deref().unwrap_or(""))?;
        write!(f, "{}", self.genre.as_deref().unwrap_or(""))?;
        Ok(())
    }
}

impl fmt::Display for MetadataError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = match self {
            MetadataError::ReadError => "Couldnt read file.",
            MetadataError::NoTag => "File has no tag",
        };
        write!(f, "{text}")
    }
}

pub trait FormatDuration {
    fn format(&self) -> String;
}

impl FormatDuration for Duration {
    fn format(&self) -> String {
        let minutes = self.as_secs() / 60;
        let seconds = self.as_secs() % 60;
        format!("{:02}:{:02}", minutes, seconds)
    }
}
