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 {LocalStorageService} from './localStorage.service';



@Injectable({ providedIn: 'root' })
export class InitGuardService implements CanActivate {
  constructor(
    private storage: LocalStorageService,
    private router: Router,
  ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const init = !!this.storage.getItem(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;
  }
}
