// MyComponent.provider.tsx
import { useEffect, useState } from 'react';
import { post } from '../../utils/post';
import { OptionsContextProvider } from './Options.context';

export const OptionsProvider = ({ options: propOptions, children }) => {
  const [options, setOptions] = useState(propOptions);

  // get the options

  useEffect(() => {
    async function getOptions() {
      const response = await post('wp_bannerize_get_options');
      setOptions(response);
    }
    getOptions();
  }, []);

  function updateOptions(path, value) {
    const newOptions = () => {
      let newData = { ...options };
      let current = newData;
      path.split('.').forEach((key, index, arr) => {
        if (index === arr.length - 1) {
          current[key] = value;
        } else {
          current[key] = { ...current[key] };
          current = current[key];
        }
      });
      return newData;
    };

    const data = newOptions();

    post('wp_bannerize_update_options', { options: JSON.stringify(data) });
    setOptions(data);
  }

  function getOptions(path) {
    return path.split('.').reduce((acc, key) => acc[key], options);
  }

  function _setOptions(newOptions) {
    post('wp_bannerize_update_options', {
      options: JSON.stringify(newOptions),
    });
    setOptions({ ...newOptions });
  }

  async function resetOptions() {
    const response = await post('wp_bannerize_get_options');
    setOptions(response);
  }

  return (
    <OptionsContextProvider
      value={{
        options,
        getOptions,
        setOptions: _setOptions,
        updateOptions,
        resetOptions,
      }}>
      {children}
    </OptionsContextProvider>
  );
};
