import { ActivatedRouteSnapshot, ResolveFn } from '@angular/router';

function findDataInActivatedRouteSnapshot(snapshot: ActivatedRouteSnapshot, data: string, depth: number) {
  if (!snapshot) {
    return;
  }

  if (snapshot.data[data]) {
    return snapshot.data[data];
  }

  if (depth > 0) {
    const children = snapshot.children;
    for (const child of children) {
      const result = findDataInActivatedRouteSnapshot(child, data, depth - 1);
      if (result) {
        return result;
      }
    }
  }
}

export const viewResolver: ResolveFn<string> = (route: ActivatedRouteSnapshot) => {
  const result = findDataInActivatedRouteSnapshot(route, 'view', 2);
  return result;
};
