import { Injectable } from '@angular/core'
import { Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

import { ModelDataService } from '../../_services/apollo.service'

@Injectable()
export class DetailResolver  {
    constructor(
        private modelDataService: ModelDataService,
        private router: Router
    ) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<object> {
        var pk = route.paramMap.get('pk')
        var modelName = route.paramMap.get('modelName')

        return this.modelDataService.resolveItemData(modelName, pk).pipe(map(
            res => {
                if (!res) {
                    this.router.navigate(['/admin', modelName])
                }
                else {
                    return res
                }
            }
        ))

    }
}
