import ADD_NOTE_MUTATION from '@/graphql/gql/mutations/addNote.gql';
import CONTENT_BLOCK_QUERY from '@/graphql/gql/queries/contentBlockQuery.gql';
import CHAPTER_QUERY from '@/graphql/gql/queries/chapterQuery.gql';
import MODULE_QUERY from '@/graphql/gql/queries/modules/moduleDetailsQuery.gql';
import INSTRUMENT_FRAGMENT from '@/graphql/gql/fragments/instrumentParts.gql';

const getBlockType = id => atob(id).split(':')[0];
const compareUuid = note => element => element.uuid === note.content;

export const constructNoteMutation = (n) => {
  let update = () => {
  };

  if (n.block) { // has a block, so it is a content block or instrument bookmark
    update = (store, {data: {addNote: {note}}}) => {
      if (n.type === 'ContentBlockNode') {
        const query = CONTENT_BLOCK_QUERY;
        const variables = {id: n.block};
        const data = store.readQuery({
          query,
          variables
        });

        const bookmarks = data.contentBlock.bookmarks;

        let index = bookmarks.findIndex(compareUuid(n));

        if (index > -1) {
          let el = bookmarks[index];
          el.note = note;
          bookmarks.splice(index, 1, el);
        }

        data.contentBlock.bookmarks = bookmarks;

        store.writeQuery({
          data,
          query,
          variables
        });
      } else {
        const fragment = INSTRUMENT_FRAGMENT;
        const id = `InstrumentNode:${n.block}`;
        const data = store.readFragment({
          fragment,
          id
        });

        const bookmarks = data.bookmarks;

        let index = bookmarks.findIndex(compareUuid(n));

        if (index > -1) {
          let el = bookmarks[index];
          el.note = note;
          bookmarks.splice(index, 1, el);
        }

        data.bookmarks = bookmarks;

        store.writeFragment({
          data,
          fragment,
          id
        });
      }
    };
  } else { // it's a chapter bookmark or a module bookmark
    update = (store, {data: {addNote: {note}}}) => {
      const type = getBlockType(n.parent) === 'ChapterNode' ? 'chapter' : 'module';
      const query = type === 'chapter' ? CHAPTER_QUERY : MODULE_QUERY;
      const variables = {id: n.parent};
      const data = store.readQuery({
        query,
        variables
      });

      const bookmark = data[type].bookmark;

      bookmark.note = note;

      data[type].bookmark = bookmark;

      store.writeQuery({
        data,
        query,
        variables
      });
    };
  }

  return {
    mutation: ADD_NOTE_MUTATION,
    variables: {
      input: {
        note: n
      }
    },
    update,
    optimisticResponse: {
      __typename: 'Mutation',
      addNote: {
        __typename: 'AddNotePayload',
        note: {
          __typename: 'NoteNode',
          id: -1,
          text: n.text
        }
      }
    }
  };
};
