import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { withReducer } from '../../app/core/with-reducer';
import { withEpics } from '../../app/core/with-epics';
import { fp as _ } from '../../common/utils/fp';
import { MarketStreams } from '../components';
import reducer, { ACTION } from '../reducer';
import * as epics from '../epics';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import {
  makeVisibilityConfigSelector,
  makeStreamsExtendedSelector,
} from '../selectors';
import { ContextMarketStreams } from '../contexts';
import { makeOfflineSelector } from '../../market/selectors';
import { TRootStateMarketStreams, TVisibility } from '../types';
import { TEntity } from '../../common/types';

type TStructured = {
  visibility: TVisibility;
  streams: TEntity;
  offline: boolean;
};

export type TPropsExternal = {
  marketCode: string;
};

type TPropsConnected = TPropsExternal &
  TStructured & {
    flush: () => void;
  };

const mapStateToProps = createStructuredSelector<
  TRootStateMarketStreams,
  TStructured
>({
  visibility: makeVisibilityConfigSelector(),
  streams: makeStreamsExtendedSelector(),
  offline: makeOfflineSelector(),
  //†prop
});
const mapDispatchToProps = {
  flush: ACTION.flush,
  //†action
};

// Uncomment to write componentDidMount hook
const Connected: React.FC<TPropsConnected> = ({
  flush,
  offline,
  streams,
  ...rest
}) => {
  useEffect(() => {
    return () => flush();
  }, []);

  if (offline) {
    return null;
  }

  return (
    <ContextMarketStreams.Provider value={{ streams }}>
      <MarketStreams {...rest} streams={streams} />
    </ContextMarketStreams.Provider>
  );
};

export default compose(
  _.hoistStatics(MarketStreams),
  withReducer('marketStreams', reducer),
  withEpics('marketStreams', epics),
  withErrorBoundary('marketStreams'),
  connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(Connected) as React.FC<TPropsExternal>;
