import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { SwUpdate, VersionEvent } from '@angular/service-worker';
import { environment } from 'src/environments/environment';
import { NotificationsService } from './services/notifications.service';

@Component({
  selector: 'diunabi-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  standalone: true,
  imports: [RouterOutlet]
})
export class AppComponent {
  constructor(
    private readonly _swUpdate: SwUpdate,
    private _notifications: NotificationsService
  ) {
    console.log('AppComponent');
    this.subscribeUpdates();
  }

  subscribeUpdates() {
    if (this._swUpdate.isEnabled && environment.production) {
      this._swUpdate.versionUpdates.subscribe((evt: VersionEvent) => {
        switch (evt.type) {
          case 'VERSION_READY': {
            this._notifications.add({
              text: "New version available. DiunaBI will restart in 10 seconds.",
              duration: 10000,
              dismiss: () => {
                window.location.reload()
              },
              btn: 'Cancel',
              action: () => {
                this._notifications.add({
                  text: "Restart canceled.",
                  btn: "Hide"
                });
              }
            })
            break;
          }
        }
      });
    }
  }
}
