import { asCodec, asObject, } from 'cleaners'



/**
 * Reads a JSON-style object into a JavaScript `Map` object with string keys.
 */
export function asMap(cleaner) {
  const asJsonObject = asObject(cleaner)

  return asCodec(
    raw => {
      const clean = asJsonObject(raw)
      const out = new Map()
      for (const key of Object.keys(clean)) out.set(key, clean[key])
      return out
    },
    clean => {
      const out = {}
      clean.forEach((value, key) => {
        out[key] = value
      })
      return asJsonObject(out)
    }
  )
}

/**
 * Reads a JSON-style object into a JavaScript `Map` object
 * with EdgeTokenId keys.
 */
export function asTokenIdMap(
  cleaner
) {
  const asJsonObject = asObject(cleaner)

  return asCodec(
    raw => {
      const clean = asJsonObject(raw)
      const out = new Map()
      for (const key of Object.keys(clean)) {
        out.set(key === '' ? null : key, clean[key])
      }
      return out
    },
    clean => {
      const out = {}
      clean.forEach((value, key) => {
        out[key == null ? '' : key] = value
      })
      return asJsonObject(out)
    }
  )
}
