import UPDATE_CONTENT_BOOKMARK from '@/graphql/gql/mutations/updateContentBookmark.gql';
import UPDATE_INSTRUMENT_BOOKMARK from '@/graphql/gql/mutations/updateInstrumentBookmark.gql';
import CONTENT_BLOCK_QUERY from '@/graphql/gql/queries/contentBlockQuery.gql';
import INSTRUMENT_FRAGMENT from '@/graphql/gql/fragments/instrumentParts.gql';

const compareUuid = uuid => element => element.uuid === uuid;

export const constructContentComponentBookmarkMutation = (uuid, bookmarked, parent, root) => {
  let mutation = {};

  if (parent.__typename === 'ContentBlockNode') {
    mutation = {
      mutation: UPDATE_CONTENT_BOOKMARK,
      variables: {
        input: {
          uuid,
          contentBlock: root,
          bookmarked
        }
      },
      update: (store, response) => {
        const query = CONTENT_BLOCK_QUERY;
        const variables = {id: root};
        const data = store.readQuery({
          query,
          variables
        });

        const bookmarks = data.contentBlock.bookmarks;

        if (bookmarked) {
          bookmarks.push({
            note: null,
            uuid,
            __typename: 'ContentBlockBookmarkNode'
          });
        } else {
          let index = bookmarks.findIndex(compareUuid(uuid));
          if (index > -1) {
            bookmarks.splice(index, 1);
          }
        }

        data.contentBlock.bookmarks = bookmarks;

        store.writeQuery({
          data,
          query,
          variables
        });
      },
      optimisticResponse: {
        __typename: 'Mutation',
        updateContentBookmark: {
          __typename: 'UpdateContentBookmarkPayload',
          success: true
        }
      }
    };
  } else {
    mutation = {
      mutation: UPDATE_INSTRUMENT_BOOKMARK,
      variables: {
        input: {
          uuid,
          instrument: root,
          bookmarked
        }
      },
      update: (store, response) => {
        const fragment = INSTRUMENT_FRAGMENT;
        const id = `InstrumentNode:${root}`;
        const data = store.readFragment({
          fragment,
          id
        });

        const bookmarks = data.bookmarks;

        if (bookmarked) {
          bookmarks.push({
            note: null,
            uuid,
            __typename: 'InstrumentBookmarkNode'
          });
        } else {
          let index = bookmarks.findIndex(compareUuid(uuid));
          if (index > -1) {
            bookmarks.splice(index, 1);
          }
        }

        data.bookmarks = bookmarks;

        store.writeFragment({
          data,
          fragment,
          id
        });
      },
      optimisticResponse: {
        __typename: 'Mutation',
        updateInstrumentBookmark: {
          __typename: 'UpdateInstrumentBookmarkPayload',
          success: true
        }
      }
    };
  }
  return mutation;
};
