use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
extern crate ab_versions as abv;

#[pyclass]
pub struct FileVersion(abv::FileVersion);

impl From<abv::FileVersion> for FileVersion {
    fn from(other: abv::FileVersion) -> Self {
        FileVersion(other)
    }
}

#[pymethods]
impl FileVersion {
    fn __str__(&self) -> PyResult<String> {
        Ok(self.0.to_string())
    }
}

/// get_version(filename, /)
/// --
///
/// This function returns the version information for an MER or APA file
/// generated By FactoryTalk View ME
#[pyfunction]
pub fn get_version(filename: &str) -> PyResult<FileVersion> {
    match abv::get_version(&filename) {
        Ok(fv) => Ok(fv.into()),
        Err(e) => Err(PyValueError::new_err(e.to_string())),
    }
}

/// get_versions(filenames, /)
/// --
///
/// This function returns a list of versions for a list of MER or APA files
/// generated By FactoryTalk View ME
#[pyfunction]
pub fn get_versions(files: Vec<&str>) -> PyResult<Vec<FileVersion>> {
    let res: Result<Vec<abv::FileVersion>, abv::FtvFileError> =
        abv::get_versions(&files).into_iter().collect();
    match res {
        Ok(fvs) => Ok(fvs.into_iter().map(|fv| fv.into()).collect()),
        Err(e) => Err(PyValueError::new_err(e.to_string())),
    }
}

/// is_protected(filename, /)
/// --
///
/// This function returns a bool if an MER file is password protected or
/// marked as "never allow conversion"
#[pyfunction]
pub fn is_protected(path: &str) -> PyResult<bool> {
    abv::is_protected(&path).map_err(|e| PyValueError::new_err(e.to_string()))
}

/// are_protected(filenames, /)
/// --
///
/// This function returns a list of bools about on if a list of MER files
/// is password protected or marked as "never allow conversion"
#[pyfunction]
pub fn are_protected(files: Vec<&str>) -> PyResult<Vec<bool>> {
    let res: Result<Vec<bool>, abv::FtvFileError> =
        abv::are_protected(&files).into_iter().collect();
    res.map_err(|e| PyValueError::new_err(e.to_string()))
}

/// strip_protection(filename, /)
/// --
///
/// This function modifies the MER file to remove any password protection
/// or unlock the file if it's marked as "never allow conversion"
#[pyfunction]
pub fn strip_protection(path: &str) -> PyResult<()> {
    abv::strip_protection(path).map_err(|e| PyValueError::new_err(e.to_string()))
}

#[pyfunction]
pub fn strip_protections(files: Vec<&str>) -> PyResult<()> {
    abv::strip_protections(&files).map_err(|e| PyValueError::new_err(e.to_string()))
}

#[pymodule]
fn ab_versions(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<FileVersion>()?;
    m.add_function(wrap_pyfunction!(get_version, m)?)?;
    m.add_function(wrap_pyfunction!(get_versions, m)?)?;
    m.add_function(wrap_pyfunction!(is_protected, m)?)?;
    m.add_function(wrap_pyfunction!(are_protected, m)?)?;
    m.add_function(wrap_pyfunction!(strip_protection, m)?)?;
    m.add_function(wrap_pyfunction!(strip_protections, m)?)?;

    Ok(())
}
