import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router'
import { LicensingComponent } from '../licensing/licensing.component'
import { Injectable } from '@angular/core'
import { LicenceService } from '../services/licence.service'

@Injectable()
export class LicensingGuard {
  constructor(
    private licenceService: LicenceService,
    private router: Router
  ) {}

  canActivate(
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot
  ): boolean {
    if (currentState?.root.queryParams.force !== undefined) return true

    if (currentState?.url.includes('licensing/update')) {
      if (!!this.licenceService.isAppActivated) return true
    }

    if (
      this.licenceService.isAppActivated.value !== null &&
      this.licenceService.isAppActivated.value === false
    ) {
      return true
    } else {
      this.router.navigateByUrl('/home')
      return false
    }
  }

  canDeactivate(
    component: LicensingComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ): boolean {
    if (currentState?.url.includes('licensing/register')) {
      return false
    }

    if (!!this.licenceService.appLocked.value) return false

    return true
    if (this.licenceService.isAppActivated.value === null) return true

    return !!this.licenceService.isAppActivated.value
  }
}
