import Locator from "../services/Locator";
import HackAttachment from "./HackAttachment.js";
import { tryToApplyFallbackFontFamily, NonWordWrapScaler, WordWrapScaler } from "../utils/utils";
import AdvancedText from "../utils/AdvancedText";

export default class TextAttachment extends HackAttachment {
  static unsupportedFontLangs = ["ru"];

  constructor(size, options) {
    super(size, options);
    this.autoScaleToFit = false;
  }

  createContent() {
    this.textObject = new AdvancedText("");
    this.textObject.on('textUpdated', () => this.update());
    this.container.addChild(this.textObject);
  }

  set transformMethod(value) {
    this.textObject.transformMethod(value);
  }

  set content(text) {
    this.textObject.content = text
  }

  set text(text) {
    this.textObject.text = text;
  }

  get text() {
    return this.textObject.text;
  }

  set style(style) {
    this.textObject.style = style;
    tryToApplyFallbackFontFamily(this.textObject);
  }

  get style() {
    return this.textObject.style;
  }

  set anchor(anchor) {
    this.textObject.anchor.set(anchor.x, anchor.y);
  }

  get anchor() {
    return { ...this.textObject.anchor };
  }

  set x(x) {
    this.textObject.x = x;
  }

  set y(y) {
    this.textObject.y = y;
  }

  center() {
    this.textObject.anchor.set(0.5);
    this.textObject.x = this.size.width * 0.5;
    this.textObject.y = this.size.height * 0.5;
  }

  alignCenter() {
    this.textObject.anchor.y = 0.5;
    this.textObject.y = this.size.height * 0.5;
  }

  alignLeft() {
    this.textObject.anchor.y = 0;
    this.textObject.y = 0;
  }

  justifyCenter() {
    this.textObject.anchor.set(0.5, 0);
    this.textObject.x = this.size.width * 0.5;
  }

  justifyLeft() {
    this.textObject.anchor.x = 0;
    this.textObject.x = 0;
  }

  justifyRight() {
    this.textObject.anchor.x = 1;
    this.textObject.x = this.size.width;
  }

  alignHorizontal(type) {
    if (type === 'left') {
      this.textObject.anchor.x = 0;
    } else if (type === 'center') {
      this.textObject.anchor.x = 0.5;
    } else if (type === 'right') {
      this.textObject.anchor.x = 1;
    }
  }

  alignVertical() {
    if ('top') {
      this.textObject.anchor.y = 0;
    } else if ('center') {
      this.textObject.anchor.y = 0.5;
    } else if ('bottom') {
      this.textObject.anchor.y = 1;
    }
  }

  scaleToFit() {
    if (this.textObject.style.wordWrap) {
      this.scaler = new WordWrapScaler(this.textObject);
    } else {
      this.scaler = new NonWordWrapScaler(this.textObject);
    }
    this.scaler.scaleToFit(this.size);
  }

  adjustUnsupportedsFontFamily(fontFamily) {
    if (TextAttachment.unsupportedFontLangs.includes(Locator.locales.currentLang)){
      this.textObject.style.fontFamily = fontFamily;
    }
  }

  update() {
    if (this.autoScaleToFit) {
      this.scaleToFit();
    }
    super.update();
  }
}
