use crate::cli::parser::DCTapArgs;
use crate::commands::base::{Command, CommandContext};
use anyhow::Result;

/// Implementation of the `dctap` command.
///
/// This struct holds the specific arguments parsed by `clap` and
/// implements the [Command] trait to execute DCTap server logic.
pub struct DctapCommand {
    /// Arguments specific to DCTap server.
    args: DCTapArgs,
}

impl DctapCommand {
    pub fn new(args: DCTapArgs) -> Self {
        Self { args }
    }
}

impl Command for DctapCommand {
    /// Returns the unique identifier for this command.
    fn name(&self) -> &'static str {
        "dctap"
    }

    /// Executes the DCTap server logic.
    ///
    /// With no `--source-file`, there is nothing new to load, so this just
    /// re-serializes whatever DCTap is already loaded in the session
    /// (useful in the interactive shell, where state persists across
    /// commands).
    fn execute(&self, ctx: &mut CommandContext) -> Result<()> {
        let format = self.args.format.into();
        let result_format = self.args.result_format.into();

        if let Some(file) = &self.args.file {
            ctx.rudof.load_dctap(file).with_dctap_format(&format).execute()?;
        }

        ctx.rudof
            .serialize_dctap(&mut ctx.writer)
            .with_result_dctap_format(&result_format)
            .execute()?;

        Ok(())
    }
}
