import { useEffect } from 'react';
import { useSetRecoilState } from 'recoil';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import rwc from 'random-weighted-choice';
import { makeUtagConfig, setCookie, getCookie } from "../../../utils/tracking/index.js";
import { utagConfig as utagAtom, variant as variantAtom } from "../../../atoms/tracking/index.js";

/**
 * Initialize the app tracking configuration.
 */
const useInitTracking = function useInitTracking(opts) {
  const {
    pib,
    baseConfig = {
      ...pib,
      appName: get(pib, 'projectName')
    },
    variants = [{
      id: 'prime',
      weight: 1
    }]
  } = opts;
  const setUtagConfig = useSetRecoilState(utagAtom);
  const setVariant = useSetRecoilState(variantAtom);
  useEffect(() => {
    if (!pib) return;
    let variant;
    const {
      id
    } = pib;
    const cookieName = `politico-interactive-variant-${id}`;

    /* Init Variant */
    if (isEmpty(variants)) {
      setVariant(null);
      variant = null;
    } else {
      const existingCookie = getCookie(cookieName);
      if (existingCookie) {
        setVariant(existingCookie);
        variant = existingCookie;
      } else {
        const randomVariantID = rwc(variants);
        setCookie(cookieName, randomVariantID, 3);
        setVariant(randomVariantID);
        variant = randomVariantID;
      }
    }

    /* Init Utag Config */
    setUtagConfig(makeUtagConfig({
      ...baseConfig,
      ab_testing: variant
    }));
  }, []);
};
export default useInitTracking;