content: import React from 'react';
  import PropTypes from 'prop-types';
  import {graphql, compose} from 'react-apollo';
  import { branch, renderComponent, withState } from 'recompose';
  import Waypoint from 'react-waypoint';
  import FETCH_ENTITY_LIST from '../queries/fetchEntityList';
  // import queryString from 'query-string';
  import StateGlobal from './StateGlobal';
  import {MainContext} from '../routes/Root';
  import {CHANGE_LOCATION_SEARCH} from '../store';
  import {locationParamObject} from '../components/utils/locationParamObject';
  import { URIComponentStrToObj } from '../routes/FilterDeductive/utils';
  // Higher Order Component принимает данные для вывода списка сущностей
  
  /*
  Пробрасываю свойства от роута /private
  в дочерние компоненты
  */
  
  
  const EntityList = (WrappedComponent) => {
    const Loading = () => (
      <span>Loading Entities...</span>
    );
  
    // Define an HoC that displays the Loading component instead of the
    // wrapped component when props.data.loading is true
    const displayLoadingState = branch(
      (props) => props.loading,
      renderComponent(Loading),
    );
  
    const renderForError = (component, propName = "data") =>
      branch(
        props => props[propName] && props[propName].error,
        renderComponent(component),
      );
  
    const ErrorComponent = props =>(
      <span>
        Something went wrong, you can try to
        <button onClick={props.refetch}>refetch</button>
      </span>
    )
  
  
    const facetPrj = withState('facetPrj', 'setfacetPrj', []);
    const hierarchy = withState('hierarchy', 'setHierarchy', []);
    const facetStr = withState('facetStr', 'setFacetStr', []);
    const facetNum = withState('facetNum', 'setFacetNum', []);
  
  
  class ComponentDecorator extends React.Component {
  
    componentDidMount(){
      const {
        location:{search},
        cluster,
        items,
        facetPrj = [],
        setHierarchy,
        setfacetPrj,
        setFacetStr,
        setFacetNum
      } = this.props;
      //это для вывода списка в каталоге
      if(search !== ''){
        const select = URIComponentStrToObj(search);
        setHierarchy(select.hierarchy);
        if(select.facetPrj){
          setfacetPrj(select.facetPrj);
        }
        if(select.facetStr){
          setFacetStr(select.facetStr);
        }
        if(select.facetNum){
          setFacetNum(select.facetNum);
        }
      }
      //это для вывода списка внутри сущности
      if(items != null){
        setfacetPrj([{cluster, items:[items]}]);
      }
  
    }
    componentDidUpdate(prevProps, prevState) {
      const {
        location:{search},
        cluster,
        items,
        facetPrj = [],
        setHierarchy,
        setfacetPrj,
        setFacetStr,
        setFacetNum
      } = this.props;
      if(prevProps.location.search !== search){
        const select = URIComponentStrToObj(search)
        setHierarchy(select.hierarchy)
  
        if(select.facetPrj){
          setfacetPrj(select.facetPrj)
        }
        if(select.facetStr){
          setFacetStr(select.facetStr);
        }
      }
      if(prevProps.facetPrj.length !== facetPrj.length){
        setfacetPrj([{cluster, items:[items]}])
      }
      // if(prevProps.facetStr.length !== facetStr.length){
      //   setFacetStr([{cluster, items:[items]}])
      // }
    }
  
  
  
    render(){
      const {
        latest,
        loadMoreEntries
      } = this.props;
  
      const handleWaypointEnter = () => {
        if (latest.entitys.length < latest.totalCount){
          loadMoreEntries();
        }
      };
  
      return(
        <WrappedComponent
          waypoint={handleWaypointEnter}
          {...this.props}
        />
      );
    }
  }
  
    const QueryWithData = graphql (FETCH_ENTITY_LIST, {
      options: ({
        selSearch,
        facetNum,
        entitiesIdArray,
        hierarchy,
        facetPrj,
        facetStr,
        projectionsDonors,
        stateGlobalQuery: {
          selHierarchy,
          selEntitiesLayout
        }
      }) => ({
        variables: {
          limit: 12,
          cursor: 0,
          hierarchy: hierarchy,
          search: selSearch,
          facetPrj,
          projectionsDonors: projectionsDonors,
          facetStr,
          facetNum,
          entitiesIdArray: entitiesIdArray
        }
      }),
      props({ data: { loading, latest, fetchMore} }){
        return {
          loading,
          latest,
          loadMoreEntries: () => {
            return fetchMore({
              query: FETCH_ENTITY_LIST,
              variables: {
                cursor: latest.cursor + latest.limit,
              },
              updateQuery: (previousResult, { fetchMoreResult }) => {
                const previousEntry = previousResult.latest.entitys;
                const newEntitys = fetchMoreResult.latest.entitys;
                const newCursor = fetchMoreResult.latest.cursor;
  
                return {
                  // By returning `cursor` here, we update the `loadMore` function
                  // to the new cursor.
                  latest: {
                    __typename: previousResult.latest.__typename,
                    totalCount: previousResult.latest.totalCount,
                    limit: previousResult.latest.limit,
                    cursor: newCursor,
                    hierarchy: previousResult.latest.hierarchy,
                    search: previousResult.latest.search,
                    entitys: [...previousEntry, ...newEntitys],
                    facetNum: previousResult.latest.facetNum,
                    facetStr: previousResult.latest.facetStr,
                    facetPrj: previousResult.latest.facetPrj,
                    facetLayout: previousResult.latest.facetLayout,
                  },
                };
              },
            });
          },
        };
      },
    });
    ComponentDecorator.propTypes = {
      latest: PropTypes.shape({
        entitys: PropTypes.array,
      }).isRequired
    };
    return compose(
      facetStr,
      facetNum,
      hierarchy,
      facetPrj,
      StateGlobal,
      QueryWithData,
      displayLoadingState,
      renderForError(ErrorComponent),
    )(ComponentDecorator);
  };
  
  export default EntityList;
  