import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TextService {
  private canvas: any;
  private context: any;

  constructor() {
    this.canvas = document.createElement('canvas');
    this.context = this.canvas.getContext('2d');

    this.context.textBaseline = 'baseline';
    this.context.fillStyle = 'rgba(0, 0, 0, 1)';
  }


  textWidth(text, options) {
    this.context.restore();
    this.context.save();
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    options = Object.assign({
      style: 'normal',
      variant: 'normal',
      weight: 'normal',
      size: 'medium',
      family: 'sans-serif',
      align: 'start',
      baseline: 'alphabetic'
    }, options);

    let size = options.size;
    if (typeof size === 'number') {
      size = size + 'px';
    }

    this.context.font = `${options.style} ${options.variant} ${options.weight} ${size} ${options.family}`;

    this.context.textAlign = options.align;
    this.context.textBaseline = options.baseline;

    return this.context.measureText(text).width;
  }

  textImage(text, options) {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    options = Object.assign({
      style: 'normal',
      variant: 'normal',
      weight: 'normal',
      size: 'medium',
      color: '#000',
      family: 'sans-serif',
      align: 'start',
      baseline: 'alphabetic'
    }, options);

    let size = options.size;
    if (typeof size === 'number') {
      size = (size) + 'px';
    }
    this.context.fillStyle = options.color;
    this.context.font = `${options.style} ${options.variant} ${options.weight} ${size} ${options.family}`;

    this.context.textAlign = options.align;
    this.context.textBaseline = options.baseline;
    const width = this.context.measureText(text).width;
    this.context.canvas.width = width;


    this.context.fillStyle = options.color;
    this.context.font = `${options.style} ${options.variant} ${options.weight} ${size} ${options.family}`;

    this.context.textAlign = options.align;
    this.context.textBaseline = options.baseline;

    // this.context.fillText(text, 0 , 0);
    this.context.fillText(text, width / 2, options.size * 2);
    // this.context.fillText(text, width, 0);
    return this.context.canvas.toDataURL('image/png');

    const image = this.context.getImageData(0, 0, width, options.size * 2);
    const tempCanvas = document.createElement('canvas');
    const tempCtx = tempCanvas.getContext('2d');

    // set the temp canvas size == the canvas size
    tempCanvas.width = image.width;
    tempCanvas.height = image.height;

    // put the modified pixels on the temp canvas
    tempCtx.putImageData(image, 0, 0);

    this.context.restore();
    return tempCanvas.toDataURL('image/png');


  }
}
