import React from 'react';
import { connect } from 'react-redux';

import { RULE_TYPE } from '../../constants.js';
import { selectRule, fetchRule } from '../../actions/rules.js';
import { fetchPostsBySection } from '../../actions/posts.js';

import { isSelected } from './functions.js';

class RuleItem extends React.Component {
  handleSelect() {
    const rule = { ...this.props.rule };

    this.props.selectRule(rule);
    this.props.fetchPostsBySection({ ...rule, type: RULE_TYPE });
    this.props.fetchRule(rule);
  }

  render() {
    const selected = isSelected(this.props.rule, this.props.selected, RULE_TYPE);
    const className = `rules__item ${selected ? 'rules__item--selected' : ''}`;
    let favicon = null;

    if (this.props.rule.favicon) {
      favicon = <img className="favicon" width="20" src={this.props.rule.favicon} />;
    } else {
      favicon = <i className="fas fa-image" />;
    }

    return (
      <li className={className} onClick={() => this.handleSelect()}>
        <div className="rules__info">
          {favicon}
          <span className="rules__title" title={this.props.rule.name}>
            {this.props.rule.name}
          </span>
        </div>
        <span className="badge">{this.props.rule.unread}</span>
      </li>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  selectRule: rule => dispatch(selectRule(rule)),
  fetchPostsBySection: section => dispatch(fetchPostsBySection(section)),
  fetchRule: rule => dispatch(fetchRule(rule)),
});

export default connect(null, mapDispatchToProps)(RuleItem);
