import { inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { ShareDataRepository } from '@app/domain/shareData/share-data.repository';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root',
})
export class WebShareService implements ShareDataRepository {
  private document = inject(DOCUMENT);
  private toastr = inject(ToastrService);

  async share(shareData: ShareData) {
    const navigator = this.document.defaultView?.navigator;

    if (navigator && navigator.canShare && navigator.canShare(shareData)) {
      try {
        await navigator.share(shareData);
        return;
      } catch (error) {
        return;
      }
    }
    this.copyToClipboard(shareData.url!);
  }

  private copyToClipboard(text: string) {
    navigator.clipboard.writeText(text).then(() => {
      this.toastr.info(`Le lien du profil est copié dans le presse papier !`, `Partage de profil`, {
        closeButton: true,
        progressAnimation: 'decreasing',
        progressBar: true,
      });
    });
  }
}
