import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { IPricingPlanModel } from '../model/pricing-plan.model';
import { PricingPlansApiService } from './pricing-plans-api.service';
import * as _moment from 'moment';

@Injectable({
  providedIn: 'root'
})
export class PricingPlanResolver  {
  constructor(private pricingPlansApiService: PricingPlansApiService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<IPricingPlanModel> | Promise<IPricingPlanModel> | IPricingPlanModel {
    return this.pricingPlansApiService.get(route.params.id).pipe(
      map(value => {
        for (const priceRule of value.pricing_rules) {
          if (priceRule.end_dt) {
            // @ts-ignore
            priceRule.end_dt = _moment(priceRule.end_dt).format();
          }
        }
        return value;
      }),
      catchError(() => of(null))
    );
  }
}
