import { Injectable, Input } from "@angular/core";
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanLoad,
  Route
} from "@angular/router";
import { InvestmentProposalForm } from "@app/models/investment-proposal-form";
import { InvestmentProposalWorkflowService } from "./investment-proposal-workflow.service";
import { FormInvestmentProposalService } from "./form-investment-proposal.service";

@Injectable({
  providedIn: "root"
})
export class WorkflowGuard implements CanActivate {
  @Input() formData: InvestmentProposalForm;

  constructor(
    private router: Router,
    private workflowService: InvestmentProposalWorkflowService,
    private formService: FormInvestmentProposalService
  ) {
    this.formData = this.formService.getFormData();
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    let path: string = route.routeConfig.path;

    return this.verifyWorkFlow(path);
  }

  verifyWorkFlow(path): boolean {
    // If any of the previous steps is invalid, go back to the first invalid step
    let firstPath = this.workflowService.getFirstInvalidStep(path);
    if (firstPath.length > 0) {
      let url = `/${firstPath}`;
      this.router.navigate([url]);
      return false;
    }

    return true;
  }
}
