import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { AuthService } from '../../auth/auth.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '../../config/config.service';
import { HttpClient } from '@angular/common/http';
import { ThemingService } from '../../ui/theming/theming.service';
import { RefreshTimer } from '../../ui-api/helpers/refresh-timer';
import { Location } from '@angular/common';
import { MatDialog } from '@angular/material/dialog';

@Component({
  selector: 'app-disconnected-from-server',
  templateUrl: './disconnected-from-server.component.html',
  styleUrls: ['./disconnected-from-server.component.scss']
})
export class DisconnectedFromServerComponent implements OnInit, OnDestroy {
  refreshTimer: RefreshTimer;
  nextUrl: string;

  constructor(
    private authService: AuthService,
    private router: Router,
    private config: ConfigService,
    private httpClient: HttpClient,
    public themingService: ThemingService,
    private location: Location,
    private ngZone: NgZone,
    private changeDetectorRef: ChangeDetectorRef,
    private activatedRoute: ActivatedRoute,
    private dialog: MatDialog,
  ) { }

  redirectIfReconnected() {
    this.authService.checkIfLoggedIn().toPromise().then(value => {
      // boolean when can connect to server and should redirect, undefined otherwise
      if (typeof value === 'boolean') {
        // this ensures user data is set and we signal the reconnect so the menu reloads
        this.authService.signalLoginCompleted();
        if (this.config.hasPrevUrl() || this.nextUrl) {
          let redirectUrl = this.config.getPrevUrl();
          if (this.nextUrl) {
            redirectUrl = this.nextUrl;
          }
          if (redirectUrl.startsWith('http')) {
            // allow only Fleio related url redirects
            if (redirectUrl.startsWith(window.location.origin)) {
              window.location.href = redirectUrl;
            } else {
              window.location.href = this.config.getPanelHomeUrl();
            }
          } else {
            this.ngZone.run(() => {
              this.router.navigateByUrl(redirectUrl).catch(() => {
              });
            });
          }
        } else {
          window.location.href = this.config.getPanelHomeUrl();
        }
      }
    }).catch((err) => {
      throw err;
    });
  }

  ngOnInit(): void {
    this.dialog.closeAll();
    this.redirectIfReconnected();
    this.refreshTimer = new RefreshTimer(this.config.getDefaultRefreshInterval(true), () => {
      this.redirectIfReconnected();
    }, this.config, this.ngZone, this.changeDetectorRef,true, true, true);
    this.activatedRoute.queryParams.subscribe(data => {
      if (data.nextUrl) {
        this.nextUrl = data.nextUrl;
      }
    });
  }

  ngOnDestroy() {
    if (this.refreshTimer) {
      this.refreshTimer.stop();
      delete this.refreshTimer;
    }
  }

}
