// @flow
import {connect} from 'react-redux';
import {find} from 'lodash';
import PostForm from '../components/PostForm';
import * as PostActions from '../actions/posts';
import {setIsSynced} from '../actions/api';

function mapStateToProps(state: Object, props: Object) {
  const {params: {id}} = props;
  const {posts: {data}, api} = state;
  const post = find(data, {id: Number(id)});

  return {post, api};
}

function mapDispatchToProps(dispatch: Function) {
  return {
    savePost: (id) => dispatch(PostActions.savePost(id)),
    updatePost: (post) => {
      dispatch(setIsSynced(false));
      dispatch(PostActions.updatePost(post));
    },
  };
}

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