use deno_ast::{parse_module, MediaType, ParseParams, SourceTextInfo};
use oden_js::{Error, Result};
use sourcemap::SourceMap;

pub fn transpile_to_javascript(path: &str, input: String) -> Result<(String, SourceMap)> {
    let text_info = SourceTextInfo::new(input.into());
    let parsed_source = parse_module(ParseParams {
        specifier: path.to_string(),
        media_type: MediaType::TypeScript,
        text_info,
        capture_tokens: true,
        maybe_syntax: None,
        scope_analysis: false,
    })
    .map_err(|e| {
        let position = e.display_position();
        Error::ParseError(
            path.into(),
            format!(
                "{} at {}:{}:{}",
                e.message(),
                path,
                position.line_number,
                position.column_number
            ),
        )
    })?;

    let options = deno_ast::EmitOptions {
        inline_source_map: false,
        source_map: true,
        ..Default::default()
    };
    let transpiled = parsed_source
        .transpile(&options)
        .map_err(|e| Error::ParseError(path.into(), e.to_string()))?;

    let source_map = transpiled.source_map.unwrap();
    let bytes = source_map.into_bytes();
    let source_map = SourceMap::from_slice(&bytes).expect("unable to parse source map");

    return Ok((transpiled.text, source_map));
}
