import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import {LocalStorageService} from './local-storage.service';
import {INIT_FLAG, LOGINTYPE} from './local-storage.namespace';


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

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