import * as React from 'react';
import { IHistoryState } from '../../Interfaces/IHistoryState';
import { IGetFeedbackRequest } from '../../Interfaces/IGetFeedbackRequest';
import { IGetFeedbackResponse } from '../../Interfaces/IGetFeedbackResponse';
import { IMessage } from '../../Interfaces/IMessage';
import { GetCircularReplacer } from '../../utils/saveload';

// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
const myWorker = window.Worker && new Worker('workers/message_worker.js');

export function UseWorker(
  state: IHistoryState,
  configurationUrl: string | undefined,
  setMessages: React.Dispatch<React.SetStateAction<IMessage[]>>): void {
  React.useEffect(() => {
    // use webworker for the stringify to avoid freezing
    myWorker.postMessage({
      state,
      url: configurationUrl ?? import.meta.env.VITE_API_GET_FEEDBACK_URL
    });

    return () => {
    };
  }, [state]);

  React.useEffect(() => {
    myWorker.onmessage = (event) => {
      setMessages(event.data as IMessage[]);
    };
  }, [setMessages]);
}
export function UseAsync(
  state: IHistoryState,
  configurationUrl: string | undefined,
  setMessages: React.Dispatch<React.SetStateAction<IMessage[]>>): void {
  React.useEffect(() => {
    const request: IGetFeedbackRequest = {
      // eslint-disable-next-line @typescript-eslint/naming-convention
      ApplicationState: state
    };
    const dataParsed = JSON.stringify(request, GetCircularReplacer());
    const url = configurationUrl ?? import.meta.env.VITE_API_GET_FEEDBACK_URL;
    fetch(url, {
      method: 'POST',
      headers: new Headers({
        // eslint-disable-next-line @typescript-eslint/naming-convention
        'Content-Type': 'application/json'
      }),
      body: dataParsed
    })
      .then(async(response) => await response.json()
      )
      .then(async(json: IGetFeedbackResponse) => {
        setMessages(json.messages);
      });
  }, [state]);
}
