import React, { createContext, useContext, useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import parseQueryString from '../utils/parseQueryString'
import fetch from 'cross-fetch'

export const FeatureFlagsContext = createContext()
export const FeatureFlagProvider = ({ url, children }) => {
  const [state, setState] = useState()

  useEffect(() => {
    fetch(url)
      .then(resp => resp.json())
      .then(json => setState(json))
  }, [])

  return (
    <FeatureFlagsContext.Provider value={state}>
      {children}
    </FeatureFlagsContext.Provider>
  )
}

FeatureFlagProvider.propTypes = {
  url: PropTypes.string.isRequired,
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node
  ]).isRequired
}

export const useFeatureFlags = expectedFeatureFlag => {
  const ctx = useContext(FeatureFlagsContext)
  let featureFlag = ctx && ctx[expectedFeatureFlag]
  if (typeof window !== 'undefined') { // should run in the client
    const queryParams = parseQueryString(window.location.search)
    if (Object.keys(queryParams).includes(expectedFeatureFlag)) {
      featureFlag = (queryParams[expectedFeatureFlag] === 'true')
      console.log(`Forcing ${expectedFeatureFlag} => ${featureFlag}`)
    }
  }
  return featureFlag
}

export const withFeatureFlags = WrappedComponent => {
  class FeatureFlagsComponent extends React.Component {
    render (props, children) {
      return (
        <FeatureFlagProvider url='https://raw.githubusercontent.com/csarnataro/feature-flags/master/feature-flag.json'>
          <WrappedComponent {...this.props} />
        </FeatureFlagProvider>
      )
    }
  }

  return FeatureFlagsComponent
}
