#[cfg(feature = "encoding")]
use crate::errors::PsdkFatherError;
#[cfg(feature = "encoding")]
use encoding::{all::GBK, Encoding};

use crate::errors::PsdkFatherResult;

#[cfg(feature = "encoding")]
pub fn quick_text_encode(
  text: impl AsRef<str>,
  charset: impl AsRef<str>,
) -> PsdkFatherResult<Vec<u8>> {
  let charset = charset.as_ref();
  let text = text.as_ref();
  let charset_lower = charset.to_lowercase();

  let text_vec = if charset_lower.starts_with("gb") {
    GBK
      .encode(text, encoding::EncoderTrap::Ignore)
      .map_err(|e| PsdkFatherError::Encoding(e.to_string()))?
  } else {
    text.as_bytes().to_vec()
  };
  Ok(text_vec)
}

#[cfg(not(feature = "encoding"))]
pub fn quick_text_encode(
  text: impl AsRef<str>,
  _charset: impl AsRef<str>,
) -> PsdkFatherResult<Vec<u8>> {
  let text = text.as_ref();

  Ok(text.as_bytes().to_vec())
}

#[cfg(feature = "encoding")]
pub fn quick_text_decode(bytes: &[u8], charset: impl AsRef<str>) -> PsdkFatherResult<String> {
  let charset = charset.as_ref();
  let charset_lower = charset.to_lowercase();

  let text = if charset_lower.starts_with("gb") {
    GBK
      .decode(bytes, encoding::DecoderTrap::Ignore)
      .map_err(|e| PsdkFatherError::Encoding(e.to_string()))?
  } else {
    String::from_utf8_lossy(bytes).to_string()
  };
  Ok(text)
}

#[cfg(not(feature = "encoding"))]
pub fn quick_text_decode(bytes: &[u8], _charset: impl AsRef<str>) -> PsdkFatherResult<String> {
  Ok(String::from_utf8_lossy(bytes).to_string())
}
