import { WorkspaceSubscriptionDialogueMessageEventRecord } from '../../../../../../../../server-services/query-records/workspace-records';
import { dialogueMessagesQuery } from '../../../../../../../../server-services/querys';
import { WorkspaceChangeSubscriptionSpecificHandler } from '../types';

export let onDeleteDialogueMessageEventSubscriptionHandler: WorkspaceChangeSubscriptionSpecificHandler =
  (cache, event: WorkspaceSubscriptionDialogueMessageEventRecord) => {
    let messages = cache.getCacheDataByRequest({
      query: dialogueMessagesQuery,
      variables: {
        peerId: event.id,
      },
    });

    if (!messages) {
      messages = [];
      cache.setCacheDataByRequest(
        {
          query: dialogueMessagesQuery,
          variables: {
            peerId: event.id,
          },
        },
        messages
      );
    }

    for (let i = 0; i < messages.length; i++) {
      if (messages[i].id == event.messageId) {
        messages.splice(i, 1);
        break;
      }
    }

    if (cache.getCacheData('messages')[event.id]) {
      delete cache.getCacheData('messages')[event.id][event.messageId];
    }
  };
