import { useMemo } from 'react';
import useWindowHash from "../useWindowHash/index.js";
import autoType from './autoType';

/**
 * Hook to parse the widow hash as a query parameter string and return the
 * resulting object.
 *
 * Note that only the last value of each query parameter is used; if the same
 * parameter is specified twice then values other than the last one are
 * discarded. For example:
 *
 * ```
 * #foo=a&foo=b => { foo: 'b' }
 * #foo=1&bar=hi&foo => { foo: '', bar: 'hi' }
 * ```
 *
 * By default this hook does some basic type casting automatically. Any value
 * that can be parsed completely as a number with `parseFloat` gets converted
 * into a number, and the case-insensitive strings `true`, `false`, `null`, and
 * `undefined` get converted into their corresponding primitive values.
 *
 * ```
 * #foo=22 => { foo: 22 }
 * #foo=true => { foo: true }
 * #foo=FALSE => { foo: false }
 * #foo=Null => { foo: null }
 * #foo=undefined => {}
 * ```
 *
 * You can disable this automatic typing by setting `options.autoType` to
 * `false`. Then every value will always be returned as a string.
 *
 * ```js
 *
 * import { useHashProps } from '@politico/interactive-style';
 * ```
 *
 * @param {Object} [options]
 *   Additional configuration:
 *   - `autoType` (boolean): if `true` (default) then the values will be
 *     automatically type-cast; if `false` then all values will be returned as
 *     strings.
 *
 * @returns {Object}
 */
const useHashProps = function useHashProps(options = {}) {
  const {
    autoType: isAutoType = true
  } = options;
  const hash = useWindowHash();
  return useMemo(() => {
    const hashQuery = new URLSearchParams(hash);
    return Object.fromEntries([...hashQuery].map(([name, value]) => [name, isAutoType ? autoType(value) : value]));
  }, [hash]);
};
export default useHashProps;