import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot,  Router, RouterStateSnapshot } from '@angular/router';
import {CanActivate} from "@angular/router";
import {INIT_FLAG} from "../data/login/localStorage.namespace";
import {BrowserStorageService} from "./localStorage.service";



@Injectable()
export class InitGuardService implements CanActivate {
  constructor(
    private storage: BrowserStorageService,
    private router: Router,
  ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const init = !!this.storage.get(INIT_FLAG);
    if (state.url.includes('login') && init) {
      this.router.navigateByUrl('/admin/index').then();
      return false;
    }
    if (!state.url.includes('login') && !init) {
      this.router.navigateByUrl('/login').then();
      return false;
    }
    return true;
  }
}
