import * as T from '../../utils/types.js'
import _ from 'lodash'

type DynamicContentPayload = {
  name: string
  data: any
  grouped?: {
    name: string
    type: 'radio' | 'select'
    matchPlace?: {
      match: object | string
      place: any
    }
  }
}

export default {
  [T.DYNAMIC_CONTENT_POPULATE](state: any, payload: DynamicContentPayload) {
    // Normalize data
    if (typeof payload.data === 'string') {
      payload.data = JSON.parse(payload.data)
    }

    if (payload.grouped && payload.grouped['name']) {
      // group = payload.grouped
      payload.data = payload['data'][payload.grouped['name']]

      if (payload.grouped.matchPlace) {
        let matchedDataIndex = _.findIndex(payload.data, payload.grouped.matchPlace.match)
        if (matchedDataIndex >= 0) {
          payload.data[matchedDataIndex] = _.merge(payload.data[matchedDataIndex], payload.grouped.matchPlace.place)
        }
      }

      payload.data = payload.data.map((data: any) => {
        return { ...data, type: payload.grouped!.type }
      })
    }

    state.dynamicContent = {
      ...state.dynamicContent,
      [payload.name]: payload.data,
    }

    if (payload.grouped) {
      state.dynamicContentGroupConfig[payload.name] = payload.grouped
    }
  },
  [T.DYNAMIC_CONTENT_SET_BY_INDEX]: (
    state: any,
    payload: {
      name: string
      elementIndex: number
      fieldIndex: number
      fieldValue: any
    }
  ) => {
    let dynamicContentFieldIndex = _.findIndex(state.dynamicContent[payload.name][payload.elementIndex].fields, {
      index: payload.fieldIndex,
    })

    dynamicContentFieldIndex = dynamicContentFieldIndex !== -1 ? dynamicContentFieldIndex : payload.fieldIndex

    if (
      dynamicContentFieldIndex !== -1 &&
      dynamicContentFieldIndex !== null &&
      dynamicContentFieldIndex !== undefined
    ) {
      state.dynamicContent[payload.name][payload.elementIndex].fields[dynamicContentFieldIndex].value =
        payload.fieldValue
    }

    // update grouping value if exists
    let groupedData = state.dynamicContentGroupConfig[payload.name]

    if (groupedData) {
      if (groupedData.ungroupPlace) {
        for (let key in groupedData.ungroupPlace) {
          let matchedGroup: any = groupedData.ungroupPlace[key].match

          if (matchedGroup !== undefined) {
            for (let mKey in matchedGroup) {
              // remove grouping matches eg: selected:true from all elements
              for (let dKey in state.dynamicContent[payload.name]) {
                delete state.dynamicContent[payload.name][dKey][mKey]
              }
              // add grouping matches to the elementIndex eg: selected: true to index 1
              state.dynamicContent[payload.name][payload.elementIndex][mKey] = matchedGroup[mKey]
            }
          }
        }
      }
    }
  },
}
