import React, { useReducer, useMemo, useContext } from "react";
import PropTypes from "prop-types";
import { obfuscate } from "../utils/obfuscateStrings";

const SensitiveInfoContext = React.createContext();

const initialState = {
  enabled: false
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "onSensitiveInfoEnabled": {
      return {
        ...state,
        enabled: action.payload.enabled
      };
    }
    default: {
      return state;
    }
  }
};

const dispatchActions = dispatch => ({
  onSensitiveInfoEnabled: enabled => dispatch({ type: "onSensitiveInfoEnabled", payload: { enabled } })
});

const useSensitiveInfo = () => {
  const { state, actions } = useContext(SensitiveInfoContext);
  const { enabled } = state;
  const { onSensitiveInfoEnabled } = actions;

  const mask = text => {
    if (!enabled) return text;
    return obfuscate(text, "◾");
  };

  const maskElements = list => {
    if (!enabled) return list;
    const maskedList = list.map(z => obfuscate(z, "◻️"));
    return maskedList;
  };

  return { enabled, onSensitiveInfoEnabled, mask, maskElements };
};

const SensitiveInfoProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const actions = useMemo(() => dispatchActions(dispatch), [dispatch]);

  return (
    <SensitiveInfoContext.Provider
      value={{
        state,
        actions
      }}
    >
      {children}
    </SensitiveInfoContext.Provider>
  );
};

SensitiveInfoProvider.propTypes = {
  children: PropTypes.node.isRequired
};

export { SensitiveInfoProvider, useSensitiveInfo };
export default SensitiveInfoProvider;
