import { interval } from 'rxjs';
import { Injectable, inject } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Injectable({ providedIn: 'root' })
export class UpdateService
{
  private readonly updates = inject(SwUpdate);

  constructor()
  {
    if (this.updates.isEnabled)
    {
      interval(60 * 60 * 1000).subscribe(() =>
      {
        this.updates.checkForUpdate().then(() => { this.promptUser(); });
      });
    }
  }

  public checkForUpdates(): void
  {
    this.updates.versionUpdates.subscribe(async evt =>
    {
      switch (evt.type)
      {
        case 'VERSION_DETECTED':
          break;

        case 'VERSION_READY':
          await this.updates.activateUpdate();
          location.reload();
          break;

        case 'VERSION_INSTALLATION_FAILED':
          console.log(`Failed to install app version '${evt.version.hash}': ${evt.error}`);
          break;
      }
    });
  }

  private promptUser(): void
  {
    this.updates.activateUpdate().then(() =>
    {
      location.reload()
    });
  }
}
