#![allow(dead_code)]
pub mod jam;
use pyo3::prelude::*;
use pyo3::types::PyBytes;

#[pyfunction]
fn encode_py(py: Python<'_>, mut data: Vec<u8>, orig: usize, rec: usize)
    -> PyResult<Vec<Vec<u8>>>
{
    let res = py.allow_threads(|| {
        jam::encode(&mut data, orig, rec)
    });

    res.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{:?}", e)))
}

#[pyfunction]
fn decode_py(
    py: Python<'_>,
    shards: Vec<(Vec<u8>, usize)>,
    orig: usize,
    rec: usize,
) -> PyResult<Vec<u8>> {
    let res = py.allow_threads(|| {
        jam::decode(shards, orig, rec)
    });

    res.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{:?}", e)))
}

#[pyfunction]
fn multi_encode_py(
    py: Python<'_>,
    segments: Vec<Py<PyBytes>>,
    orig: usize,
    rec: usize,
) -> PyResult<Vec<Vec<Vec<u8>>>> 
    {
    let mut owned: Vec<Vec<u8>> = Vec::with_capacity(segments.len());

    for b in &segments {
        let bytes = b.bind(py);
        owned.push(bytes.as_bytes().to_vec());
    }

    let res = py.allow_threads(|| {
        jam::multi_encoder(owned, orig, rec)
    });

    res.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{:?}", e)))
}

#[pymodule]
fn tsrkit_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(encode_py, m)?)?;
    m.add_function(wrap_pyfunction!(decode_py, m)?)?;
    m.add_function(wrap_pyfunction!(multi_encode_py, m)?)?;
    Ok(())
}