use crate::marks::{Alignment, Font, Rotation};
use psdk_father::args::{ArgContext, PsdkArgBase, PsdkEasyArg};
use psdk_father::command::{CommandClause, PsdkTextCommand};
use psdk_father::errors::PsdkFatherResult;
use psdk_father::types::psdk_types::PsdkPrinterCommandEnumValue;
use std::sync::{Arc, Mutex};

#[derive(Clone, Debug)]
pub struct TTextOptions {
  /// 文字起始x坐标
  pub x: i32,
  /// 文字起始y坐标
  pub y: i32,
  // 打印的文本内容
  pub content: String,
  /// 文字字体(默认TSS16)
  pub font: Option<Font>,
  /// 自定义字体
  pub raw_font: Option<String>,
  /// 文字旋转角度(默认不旋转)
  pub rotation: Option<Rotation>,
  /// 文字横向放大倍数
  pub x_multi: Option<i32>,
  /// 文字纵向放大倍数
  pub y_multi: Option<i32>,
  /// 文字是否加粗(默认不加粗)
  pub bold: Option<bool>,
  pub alignment: Option<Alignment>,
}

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

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

impl<T: Into<String>> From<(i32, i32, i32, i32, bool, T)> for TText {
  fn from((x, y, x_multi, y_multi, bold, content): (i32, i32, i32, i32, bool, T)) -> Self {
    Self::new(TTextOptions {
      x,
      y,
      content: content.into(),
      font: None,
      raw_font: None,
      rotation: None,
      x_multi: Some(x_multi),
      y_multi: Some(y_multi),
      bold: Some(bold),
      alignment: None,
    })
  }
}

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

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

  fn clause(&self) -> PsdkFatherResult<CommandClause> {
    let font = self.options.raw_font.clone().unwrap_or_else(|| {
      self
        .options
        .font
        .clone()
        .unwrap_or(Font::TSS16)
        .command_value()
    });
    let rotation = self.options.rotation.clone().unwrap_or(Rotation::Rotation0);
    let bold = self.options.bold.unwrap_or(false);
    let alignment = self.options.alignment.clone().unwrap_or(Alignment::Default);
    let x_multi = self.options.x_multi.unwrap_or(1);
    let y_multi = self.options.y_multi.unwrap_or(1);
    let mut ptc = PsdkTextCommand::with_header_format_tspl(self.header());
    ptc
      .append(self.options.x)
      .append(self.options.y)
      .append_with_quote(font)
      .append(rotation.command_value())
      .append(x_multi)
      .append(y_multi);
    if bold {
      ptc.append("B1");
    }
    if alignment != Alignment::Default {
      ptc.append(alignment.command_value());
    }
    ptc.append_with_quote(&self.options.content);

    Ok(ptc.clause())
  }
}

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