/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {Component, ElementRef, HostBinding, OnDestroy, ViewChild} from '@angular/core';
import {InternetConnectionService} from '../../../util/internet-connection.service';
import {Subscription} from 'rxjs';
import {Router} from '@angular/router';
import {NGXLogger} from 'ngx-logger';

@Component({
  selector: 'stapps-offline-notice',
  templateUrl: 'offline-notice.html',
  styleUrls: ['offline-notice.scss'],
})
export class OfflineNoticeComponent implements OnDestroy {
  @HostBinding('class.is-offline') isOffline = false;

  @HostBinding('class.has-error') hasError = false;

  @ViewChild('spinIcon', {read: ElementRef}) spinIcon: ElementRef;

  readonly subscriptions: Subscription[];

  constructor(
    readonly offlineProvider: InternetConnectionService,
    readonly router: Router,
    readonly logger: NGXLogger,
  ) {
    this.subscriptions = [
      this.offlineProvider.offline$.subscribe(isOffline => {
        this.isOffline = isOffline;
      }),
      this.offlineProvider.error$.subscribe(hasError => {
        this.hasError = hasError;
      }),
    ];
  }

  retry() {
    this.spinIcon.nativeElement.classList.remove('spin');
    this.spinIcon.nativeElement.offsetWidth;
    this.spinIcon.nativeElement.classList.add('spin');
    this.offlineProvider.retry();
  }

  ngOnDestroy() {
    for (const subscription of this.subscriptions) {
      subscription.unsubscribe();
    }
  }
}
