import processors from './processors'
import { Element, Processor } from '../'

/**
 * Value Processor
 *
 * Processes dynamic field elements to assign is dynamic value in a component
 * readable form
 */
export default class ValueProcessor implements Processor {
  private processors: ValueProcessorItem[]

  constructor(private rootState: any, private rootGetters: any) {
    this.processors = processors.map(
      (process: any): ValueProcessorItem => {
        return new process()
      }
    )
  }

  /**
   * Process Element
   *
   * Runs the element through all the value processors. The element will be modified hence any changes
   * mutated to the state after processing will not be reactive after processing
   *
   * @param element
   * @param index
   */
  public processElement(element: Element, index: number) {
    this.processors.forEach((process: ValueProcessorItem) => {
      // value processor will update the element to create one that is representable by the component
      // so we will remove the observers from the child element to make it modifiable
      element = JSON.parse(JSON.stringify(element))
      element = process.processValue(element, index, this.rootState, this.rootGetters)
    })

    return element
  }
}

export interface ValueProcessorItem {
  processValue(element: Element, index: number, rootState: any, rootGetters: any): Element
}
