import _slicedToArray from "@babel/runtime/helpers/slicedToArray";

/* eslint-disable react-hooks/exhaustive-deps */

/* eslint-disable react/no-multi-comp */
import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import ReactGA from "react-ga";
import produce from "immer";
import ModuleLoader from "../../ModuleLoader";
import { launchAction } from "../../../utils/redux";
import { init } from "../../../utils/tracking/analytics";
var INIT_ANALYTICS = "INIT_ANALYTICS";
var defaultState = {
  isInit: false,
  isSandbox: true,
  options: {},
  id: false
};

var Analytics = function Analytics(_ref) {
  var analyticsId = _ref.analyticsId,
      sandbox = _ref.sandbox,
      dispatch = _ref.dispatch,
      options = _ref.options,
      children = _ref.children;

  var _useState = useState(true),
      _useState2 = _slicedToArray(_useState, 2),
      isLoading = _useState2[0],
      setIsLoading = _useState2[1];

  useEffect(function () {
    if (!sandbox || !analyticsId || analyticsId.trim().length > 0) {
      ReactGA.initialize(analyticsId, options);
    }

    window.analyticsConfig = {
      options: options,
      id: analyticsId,
      isSandbox: sandbox
    };
    init({
      options: options,
      id: analyticsId,
      isSandbox: sandbox
    });
    launchAction(dispatch, INIT_ANALYTICS, {
      options: options,
      id: analyticsId,
      isSandbox: sandbox
    });
    setIsLoading(false);
  }, [analyticsId, sandbox, options]);
  if (isLoading) return /*#__PURE__*/React.createElement(React.Fragment, null);
  return /*#__PURE__*/React.createElement(React.Fragment, null, children);
};

Analytics.propTypes = {
  analyticsId: PropTypes.string,
  sandbox: PropTypes.bool,
  options: PropTypes.instanceOf(Object)
};
Analytics.defaultProps = {
  analyticsId: "",
  sandbox: false,
  options: {}
};

var Reducer = function Reducer(state, action) {
  return produce(state || defaultState, function (possibleState) {
    switch (action.type) {
      case INIT_ANALYTICS:
        {
          possibleState.options = action.payload.options;
          possibleState.id = action.payload.id;
          possibleState.isSandbox = action.payload.isSandbox;
          possibleState.isInit = true;
          break;
        }

      default:
        {// Do nothing
        }
    }
  });
};

var moduleConfig = {
  id: "AnalyticsExtension",
  reducerMap: {
    analyticsExtension: Reducer
  },
  initialActions: [],
  finalActions: []
};
export default (function (props) {
  return /*#__PURE__*/React.createElement(ModuleLoader, {
    Component: connect()(Analytics),
    config: moduleConfig,
    componentProps: props
  });
});