import { PDFPage, PDFFont, rgb, RGB } from 'pdf-lib';
import { PDFElement, Size } from './PDFElement.js';
import { Margin, Padding } from './Layout.js';

export interface TextOptions {
  font: PDFFont;
  fontSize?: number;
  color?: RGB;
	margin?: Margin,
	padding?: Padding,
	lineHeight?: number
}

export class Text extends PDFElement {
  private content: string;
  private font: PDFFont;
  private fontSize: number;
  private color: RGB;
	private options: TextOptions

	protected _width: number;
	protected _height: number;

	public padding: Padding
	public margin: Margin

  constructor(content: string, options: TextOptions) {
    super();
    this.content = content;
    this.font = options.font;
    this.fontSize = options.fontSize ?? 12;
    this.color = options.color ?? rgb(0, 0, 0);
    this._width = this.font.widthOfTextAtSize(content, this.fontSize);
    this._height = options.lineHeight || this.font.heightAtSize(this.fontSize);
		this.options = options;
		this.margin = this.options.margin || { top: 0, left: 0, right: 0, bottom: 0}
		this.padding = this.options.padding || { top: 0, left: 0, right: 0, bottom: 0}
  }

	addChild(...children: PDFElement[]): void {
		throw new Error("Cannot add child element to Text")
	}

	get height() {
		return this._height + this.padding.top + this.padding.bottom;
	}

	get width() {
		return this._width + this.padding.left + this.padding.right;
	}

  draw(page: PDFPage, x: number, y: number): void {
    page.drawText(this.content, {
      x: x + this.margin.left + this.padding.left,
      y: y - this.height - this.margin.top - this.padding.top,
      size: this.fontSize,
      font: this.font,
      color: this.color
    });
  }
}
