import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  Resolve,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { catchError, Observable, throwError } from 'rxjs';

import { Message } from '../models/message';
import { MessagePagination } from '../models/message-pagination';
import { MessageService } from '../services/message.service';

@Injectable({
  providedIn: 'root',
})
export class MessageResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(
    private _messageService: MessageService,
    private _router: Router
  ) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Message | undefined> {
    return this._messageService.getMessageById(route.paramMap.get('id')).pipe(
      // Error here means the requested product is not available
      catchError((error) => {
        // Log the error
        console.error(error);

        // Get the parent url
        const parentUrl = state.url.split('/').slice(0, -1).join('/');

        // Navigate to there
        this._router.navigateByUrl(parentUrl);

        // Throw an error
        return throwError(error);
      })
    );
  }
}

@Injectable({
  providedIn: 'root',
})
export class MessagesResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _messageService: MessageService) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: MessagePagination;
    messages: Message[];
  }> {
    return this._messageService.getMessages();
  }
}
