import { Injectable } from '@angular/core'
import { SwUpdate } from '@angular/service-worker'

@Injectable({
  providedIn: 'root'
})
export class AppUpdateService {
  constructor(
    private readonly updates: SwUpdate,
  ) {
    this.updates.versionUpdates.subscribe(
      evt => {
        switch (evt.type) {
          case 'VERSION_DETECTED':
            console.log(`Downloading new app version: ${evt.version.hash}`);
            break;
          case 'VERSION_READY':
            console.log(`Current app version: ${evt.currentVersion.hash}`);
            console.log(`New app version ready for use: ${evt.latestVersion.hash}`);
            this.showAppUpdateAlert()
            break;
          case 'VERSION_INSTALLATION_FAILED':
            console.log(`Failed to install app version '${evt.version.hash}': ${evt.error}`);
            break;
        }
      }
    )
  }

  showAppUpdateAlert() {
    const message = 'App Update available - click OK to update'
    alert(message)
    this.doAppUpdate()
  }

  doAppUpdate() {
    this.updates.activateUpdate().then(() => document.location.reload())
  }
}