import { clone } from "ramda"
const chainMongoFind = (_params, chain = "$and") => {
  const params = clone(_params)
  if (!params.find) {
    params.find = {}
  }
  if (!params.find.$and) {
    const oldFinds = Object.keys(params.find)
    params.find[chain] = []
    oldFinds.forEach((find) => {
      const newAndFind = {}
      newAndFind[find] = params.find[find]
      params.find[chain].push(newAndFind)
      delete params.find[find]
    })
  }
  return params
}

const applyDataFieldToQuery = (find, values: any = [], field) => {
  if (values.length === 0) return find

  const addTypes = (wrapper, values, isArray) => {
    if (isArray) {
      const block = {}
      block[field] = {}
      if (values.length > 1) {
        block[field] = { $in: values }
        wrapper.push(block)
      }
      if (values.length === 1) {
        block[field] = { $eq: values[0] }
        wrapper.push(block)
      }
    } else {
      if (values.length > 1) {
        wrapper[field] = { $in: values }
      }
      if (values.length === 1) {
        wrapper[field] = { $eq: values[0] }
      }
    }

    return wrapper
  }
  if (Object.keys(find).length === 0) {
    find = addTypes(find, values, false)
  } else {
    if (find.$and) {
      find.$and = addTypes(find.$and, values, true)
    }
    if (!find.$and) {
      find = chainMongoFind({ find }).find
      find.$and = addTypes(find.$and, values, true)
    }
  }

  return find
}

export { applyDataFieldToQuery, chainMongoFind }
