use std::collections::HashMap;
use crate::{
    config::Config,
    model::auth::{ConnectionType, ExternalConnectionInfo, UserConnections},
};
use md5::{Md5, Digest};
use base16ct::upper::encode_string;

/// A connection to last.fm.
pub struct LastFmConnection(pub UserConnections, pub Config);

impl LastFmConnection {
    /// Create a legacy MD5 signature, since last.fm is old.
    pub fn signature(params: HashMap<String, String>, secret: String) -> String {
        let mut params_string = String::new();

        let mut params = params.clone();
        params.remove("format");

        let mut x = params.iter().collect::<Vec<(&String, &String)>>();
        x.sort_by(|a, b| a.0.cmp(b.0));

        for param in x {
            params_string.push_str(&format!("{}{}", param.0, param.1));
        }

        let mut hasher = Md5::new();
        hasher.update(format!("{params_string}{secret}"));

        let hash = hasher.finalize();
        encode_string(&hash)
    }

    /// Create a new [`ExternalConnectionInfo`] for the connection.
    pub fn connection() -> ExternalConnectionInfo {
        ExternalConnectionInfo {
            con_type: ConnectionType::Token,
            data: HashMap::new(),
            show_on_profile: true,
        }
    }
}
