import * as _ from 'lodash'
import {ApiResponse, DataProviderArgs, EnumChoice, EnumChoices, Processor} from '~/types/interfaces'
import BaseProcessor from '~/services/data/processor/baseProcessor'
import { QUERY_TYPE } from '~/types/enums'

class EnumProcessor extends BaseProcessor implements Processor {

  /**
   * Is the given argument a supported model
   * @param args
   */
  public static support (args:DataProviderArgs): boolean {
    return args.type === QUERY_TYPE.ENUM
  }

  /**
   *
   * @param data
   */
  // eslint-disable-next-line require-await
  async process (payload: ApiResponse): Promise<any> {
    const enums: EnumChoices = []

    _.each(payload.data.items, (item, key) => {
      const entry:EnumChoice = {
        value: key,
        label: this.ctx.app.i18n.t(item) as string
      }
      enums.push(entry)
    })
    return EnumProcessor.sortEnum(enums)
  }

  /**
   * Sort the given enum by its elements labels
   * @param enums
   * @private
   */
  private static sortEnum (enums: EnumChoices) {
    return enums.sort((a, b) => {
      if (a.label > b.label) { return 1 }
      if (a.label < b.label) { return -1 }
      return 0
    })
  }
}

export default EnumProcessor
