use crate::aes::Aesthetic;
use crate::data::Value;
use crate::render::backend::Linetype;

use super::Scale;

/// Manual linetype scale — maps named levels to user-specified linetypes.
#[derive(Clone, Debug)]
pub struct ScaleLinetypeManual {
    name: String,
    levels: Vec<String>,
    linetypes: Vec<Linetype>,
}

impl ScaleLinetypeManual {
    pub fn new(values: Vec<(&str, Linetype)>) -> Self {
        let levels: Vec<String> = values.iter().map(|(k, _)| k.to_string()).collect();
        let linetypes: Vec<Linetype> = values.iter().map(|(_, lt)| *lt).collect();
        ScaleLinetypeManual {
            name: String::new(),
            levels,
            linetypes,
        }
    }
}

impl Scale for ScaleLinetypeManual {
    fn aesthetic(&self) -> Aesthetic {
        Aesthetic::Linetype
    }

    fn train(&mut self, values: &[Value]) {
        for v in values {
            let key = v.to_group_key();
            if !self.levels.contains(&key) {
                self.levels.push(key);
            }
        }
    }

    fn map(&self, value: &Value) -> f64 {
        let key = value.to_group_key();
        self.levels
            .iter()
            .position(|l| l == &key)
            .map(|i| i as f64)
            .unwrap_or(0.0)
    }

    fn breaks(&self) -> Vec<(f64, String)> {
        self.levels
            .iter()
            .enumerate()
            .map(|(i, label)| (i as f64, label.clone()))
            .collect()
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn set_name(&mut self, name: &str) {
        self.name = name.to_string();
    }

    fn is_discrete(&self) -> bool {
        true
    }

    fn map_to_linetype(&self, value: &Value) -> Option<Linetype> {
        let key = value.to_group_key();
        let idx = self.levels.iter().position(|l| l == &key).unwrap_or(0);
        if idx < self.linetypes.len() {
            Some(self.linetypes[idx])
        } else {
            Some(self.linetypes[idx % self.linetypes.len()])
        }
    }

    fn clone_box(&self) -> Box<dyn Scale> {
        Box::new(self.clone())
    }

    fn reset_training(&mut self) {
        self.levels.clear();
    }
}
