use std::path::Path;

use serde_derive::{Deserialize, Serialize};
use shapemap::ShapemapConfig;
use srdf::RdfDataConfig;

use crate::{ShExConfig, ValidatorError, MAX_STEPS};

/// This struct can be used to customize the behavour of ShEx validators
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]

pub struct ValidatorConfig {
    /// Maximum numbers of validation steps
    pub max_steps: usize,

    /// Configuration of RDF data readers
    pub rdf_data: Option<RdfDataConfig>,

    /// Configuration of ShEx schemas
    pub shex: Option<ShExConfig>,

    /// Configuration of Shapemaps
    pub shapemap: Option<ShapemapConfig>,
}

impl Default for ValidatorConfig {
    fn default() -> Self {
        Self {
            max_steps: MAX_STEPS,
            rdf_data: Some(RdfDataConfig::default()),
            shex: Some(ShExConfig::default()),
            shapemap: Some(ShapemapConfig::default()),
        }
    }
}

impl ValidatorConfig {
    /// Obtain a `ValidatorConfig` from a path file in YAML format
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<ValidatorConfig, ValidatorError> {
        let path_name = path.as_ref().display().to_string();
        let f = std::fs::File::open(path).map_err(|e| {
            ValidatorError::ValidatorConfigFromPathError {
                path: path_name.clone(),
                error: e.to_string(),
            }
        })?;
        let config: ValidatorConfig =
            serde_yml::from_reader(f).map_err(|e| ValidatorError::ValidatorConfigYamlError {
                path: path_name.clone(),
                error: e.to_string(),
            })?;
        Ok(config)
    }

    pub fn set_max_steps(&mut self, max_steps: usize) {
        self.max_steps = max_steps;
    }

    pub fn max_steps(&self) -> usize {
        self.max_steps
    }

    pub fn rdf_data_config(&self) -> RdfDataConfig {
        match &self.rdf_data {
            None => RdfDataConfig::default(),
            Some(sc) => sc.clone(),
        }
    }

    pub fn shex_config(&self) -> ShExConfig {
        match &self.shex {
            None => ShExConfig::default(),
            Some(sc) => sc.clone(),
        }
    }

    pub fn shapemap_config(&self) -> ShapemapConfig {
        match &self.shapemap {
            None => ShapemapConfig::default(),
            Some(sc) => sc.clone(),
        }
    }
}
