import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({ providedIn: 'root' })
export class ClipboardService {
  private dom: Document;

  constructor(@Inject(DOCUMENT) dom: Document) {
    this.dom = dom;
  }

  copy(value: string): Promise<string> {
    const promise = new Promise<string>((resolve, reject): void => {
      let textarea: HTMLTextAreaElement;

      try {
        // create element
        textarea = this.dom.createElement('textarea');

        // make element invisible in DOM
        textarea.style.width = '0px';
        textarea.style.height = '0px';
        textarea.style.left = '-100px';
        textarea.style.opacity = '0';
        textarea.style.position = 'fixed';
        textarea.style.top = '-100px';

        this.dom.body.appendChild(textarea);

        // set and select the element
        textarea.value = value;
        textarea.select();

        // initiate copy command on document
        this.dom.execCommand('copy');

        resolve(value);
      } finally {
        // remove textarea from dom afterwards
        if (textarea && textarea.parentNode) {
          textarea.parentNode.removeChild(textarea);
        }
      }
    });

    return promise;
  }
}
