import React from 'react';

import { connect } from 'react-redux';
import { isEqual } from 'lodash';

import { fetchCategories } from './actions/categories';

import Sidebar from './components/sidebar/Sidebar.js';
import PostList from './components/postlist/PostList.js';
import PostModal from './components/PostModal.js';
import Messages from '../../components/Messages.js';

class App extends React.Component {
  componentDidMount() {
    this.props.fetchCategories();
  }

  render() {
    return (
      <>
        <Sidebar />
        <PostList
          feedUrl={this.props.feedUrl}
          subredditUrl={this.props.subredditUrl}
          timelineUrl={this.props.timelineUrl}
          timezone={this.props.timezone}
        />

        {!isEqual(this.props.post, {}) && (
          <PostModal
            post={this.props.post}
            rule={this.props.rule}
            category={this.props.category}
            selectedType={this.props.selectedType}
            feedUrl={this.props.feedUrl}
            subredditUrl={this.props.subredditUrl}
            timelineUrl={this.props.timelineUrl}
            categoriesUrl={this.props.categoriesUrl}
            timezone={this.props.timezone}
            autoMarking={this.props.autoMarking}
          />
        )}

        {this.props.error && (
          <Messages messages={[{ type: 'error', text: this.props.error.message }]} />
        )}
      </>
    );
  }
}

const mapStateToProps = state => {
  const { error } = state.error;

  if (!isEqual(state.selected.post, {})) {
    const ruleId = state.selected.post.rule;

    const rule = state.rules.items[ruleId];
    const category = state.categories.items[rule.category];

    return {
      category,
      error,
      rule,
      post: state.selected.post,
      selectedType: state.selected.item.type,
    };
  }

  return { error, post: state.selected.post };
};

const mapDispatchToProps = dispatch => ({
  fetchCategories: () => dispatch(fetchCategories()),
});

export default connect(mapStateToProps, mapDispatchToProps)(App);
