use std::sync::{Arc, Mutex};

use psdk_father::{
  args::{ArgContext, PsdkArgBase, PsdkEasyArg},
  command::{CommandClause, PsdkTextCommand},
  errors::PsdkFatherResult,
};

#[derive(Clone, Debug)]
pub struct TReferenceOptions {
  pub horizontal: Option<i32>,
  pub vertical: Option<i32>,
}

#[derive(Clone, Debug)]
pub struct TReference {
  options: TReferenceOptions,
  ctx: Arc<Mutex<ArgContext>>,
}

impl TReference {
  pub fn new(options: TReferenceOptions) -> Self {
    Self {
      options,
      ctx: Default::default(),
    }
  }
}

impl Default for TReference {
  fn default() -> Self {
    Self::new(TReferenceOptions {
      horizontal: None,
      vertical: None,
    })
  }
}

impl From<(i32, i32)> for TReference {
  fn from((horizontal, vertical): (i32, i32)) -> Self {
    Self::new(TReferenceOptions {
      horizontal: Some(horizontal),
      vertical: Some(vertical),
    })
  }
}

impl PsdkEasyArg<String> for TReference {
  fn context(&self) -> Arc<Mutex<ArgContext>> {
    self.ctx.clone()
  }
}

impl PsdkArgBase<String> for TReference {
  fn header(&self) -> String {
    "REFERENCE".to_string()
  }

  fn clause(&self) -> PsdkFatherResult<CommandClause> {
    let horizontal = self.options.horizontal.unwrap_or(0);
    let vertical = self.options.vertical.unwrap_or(0);
    let mut ptc = PsdkTextCommand::with_header_format_tspl(self.header());
    ptc.append(horizontal).append(vertical);
    Ok(ptc.clause())
  }
}

psdk_father::impl_psdk_arg_to_easy_arg!(String, TReference, true);
