use crate::lyrics_api::lrclib::strip_timestamp;

use super::lrclib::LrcLibResponse;
use serde::Serialize;

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", content = "lyrics")]
pub enum Response {
    SyncedLyrics { synced: String, plain: String },
    UnsyncedLyrics(String),
    IsInstrumental,
    None,
}

pub struct ResponseError {
    message: String,
}

impl ResponseError {
    pub fn new(message: String) -> Self {
        Self { message }
    }
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl Response {
    pub fn from_raw_lrclib_response(raw: LrcLibResponse) -> Self {
        match (raw.synced_lyrics(), raw.plain_lyrics(), raw.instrumental()) {
            (Some(synced), plain, _) => Response::SyncedLyrics {
                plain: plain
                    .map(|p| p.to_string())
                    .unwrap_or_else(|| strip_timestamp(synced)),
                synced: synced.to_owned(),
            },
            (None, Some(plain), _) => Response::UnsyncedLyrics(plain.to_owned()),
            (None, None, true) => Response::IsInstrumental,
            (None, None, false) => Response::None,
        }
    }

    pub fn output(&self) -> Option<&str> {
        match self {
            Response::SyncedLyrics { synced, .. } => Some(synced),
            Response::UnsyncedLyrics(unsynced) => Some(unsynced),
            _ => None,
        }
    }
}
