import { TileAbstractController } from '../tile.abstract.controller';

enum TargetOptions {
  self = 'self',
  blank = 'blank',
  download = 'download'
}

export class TileDownloadController extends TileAbstractController {
  /** */
  public target: TargetOptions = TargetOptions.self;
  /** */
  public clickHandler(): void {
    if (this.target === TargetOptions.blank) {
      this.openInNewTab();
    } else if (this.target === TargetOptions.download) {
      this.downloadDirectly();
    } else {
      super.clickHandler();
    }
  }
  /**
   * Open the file in a new tab
   */
  public openInNewTab(): void {
    const el = this.getElement();
    el.target = '_blank';
    document.body.appendChild(el);
    el.click();
    document.body.removeChild(el);
  }
  /**
   * Download the file directly without opening in any window or tab
   */
  public downloadDirectly(): void {
    const el = this.getElement();
    el.download = '';
    document.body.appendChild(el);
    el.click();
    document.body.removeChild(el);
  }
  /**
   * Get a dummy HTMLAnchroElement
   */
  private getElement(): HTMLAnchorElement {
    const el = document.createElement('a');
    el.href = this.link;
    // Fake the elements visibility to trick browsers
    el.style.opacity = '.0000000000001';
    el.style.position = 'absolute';
    return el;
  }
}
