import { Injectable } from '@angular/core';
import {Parameter} from "../../models/Parameter";
import {
  AnyDateParameterResolver, AnyNumberParameterResolver, EndDayParameterResolver,
  IParameterResolver,
  NowDateParameterResolver, QueryStringParameterResolver,
  StartDayParameterResolver,
  AnyDateChoosenByUserParameterResolver, AnyIntervalParameterResolver, AnyIntervalChhosenByUserParameterResolver,
  AnyStringParameterResolver
} from "./IParameterResolver";
import {TranslateService} from "@ngx-translate/core";
import {ActivatedRoute} from "@angular/router";

@Injectable({
  providedIn: 'root'
})
export class ParameterResolverService {

  resolvers: IParameterResolver[] = [];

  constructor(translate: TranslateService, private activatedRoute: ActivatedRoute) {
    this.register();
  }

  register() {
    this.resolvers = [
      new AnyDateChoosenByUserParameterResolver(),
      new AnyIntervalParameterResolver(),
      new AnyIntervalChhosenByUserParameterResolver(),
      new AnyDateParameterResolver(),
      new NowDateParameterResolver(),
      new StartDayParameterResolver(),
      new EndDayParameterResolver(),
      new AnyNumberParameterResolver(),
      new QueryStringParameterResolver(),
      new AnyStringParameterResolver()
    ];
  }

  public getResolversByDataType(type?: string) {

    return this.resolvers
        .filter(o => o.allowedDataTypes.indexOf(type || '') >= 0);
  }

  public getResolverForParameter(parameter: Parameter): IParameterResolver | null {
    const resolvers = this.resolvers.filter(o => o.type.indexOf(parameter.type || '') >= 0);
    if (resolvers.length > 0)
      return resolvers[0].for(parameter, this.activatedRoute.snapshot.queryParams);
    return null;
  }

  public getParameterOptionsByDataType(dataType?: string): {type: string, description: string}[] {

    return this.getResolversByDataType(dataType)
        .map(o => <{type: string, description: string}>{ type: o.type, description: o.description });
  }

  public resolve(parameter: Parameter): any {
    const resolver = this.getResolverForParameter(parameter);
    if (!resolver)
      return null;
    return resolver.resolve();
  }
}
