import classNames from 'classnames';
import { F } from '../../shared/i18n';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import React, { PureComponent } from 'react';
import styles from './Actions.module.css';

@graphql(gql`
  mutation favoriteContentRemote($from_user: String!, $post_id: String!, $favorited: Boolean!) {
    favoriteContentRemote(from_user: $from_user, post_id: $post_id, favorited: $favorited) {
      from_user
      post_id
      favorited
    }
  }
`)
class Favorite extends PureComponent {
  handleFavorite = async evt => {
    evt.preventDefault();

    const { favorited, from_user, post_id } = this.props.contentRemote;
    const data = { from_user, post_id, favorited: !favorited };

    await this.props.mutate({
      variables: data,
      optimisticResponse: {
        __typename: 'Mutation',
        favoriteContentRemote: Object.assign({}, data, { __typename: 'ContentRemote' }),
      },
    });
  };

  render() {
    return (
      <a
        href="#favorite"
        onClick={this.handleFavorite}
        className={classNames({ [styles.enabled]: this.props.contentRemote.favorited })}
      >
        <F msg="favorite" />
      </a>
    );
  }
}

export { Favorite };

@@ -675,20 +675,25 @@
   const 
-data
+variables
  = %7B fro
@@ -784,14 +784,8 @@
 bles
-: data
 ,%0A  
@@ -895,12 +895,17 @@
 %7B%7D, 
-data
+variables
 , %7B 
@@ -945,16 +945,410 @@
      %7D,%0A
+      update: (store, %7B data: %7B favoriteContentRemote %7D %7D) =%3E %7B%0A        const query = gql%60%0A          %7B%0A            fetchUserTotalCounts %7B%0A              favoritesCount%0A            %7D%0A          %7D%0A        %60;%0A        const data = store.readQuery(%7B query %7D);%0A        data.fetchUserTotalCounts.favoritesCount += variables.favorited ? 1 : -1;%0A        store.writeQuery(%7B query: query, data %7D);%0A      %7D,%0A
     %7D);%0A

update favorite count after mutation