import React from "react";
import { EditorContext } from "./../../../ricos-context/index.js";
import { isOfType } from "../../ts-utils.js";
import { useAiRequestService } from "../../utils/use-ai-request-service.js";
const useAiImageModalActions = ({
  state,
  dispatch,
  getGatewayBaseUrl,
  appDefId,
  focusInputArea,
  saveImageStyle,
  savedConvertedPromptHelperValue,
  setConvertedPromptHelperVisible,
  publishModalAction
}) => {
  const { adapter, getPublicCommands } = React.useContext(EditorContext);
  const config = React.useMemo(
    () => ({ type: "ai", getGatewayBaseUrl, appDefId }),
    [getGatewayBaseUrl, appDefId]
  );
  const { fetchImagePrompt, fetchPromptFromSelection } = useAiRequestService(config);
  const setPromptValue = React.useCallback((value) => {
    dispatch({
      type: "SET_PROMPT_VALUE",
      payload: {
        value
      }
    });
  }, []);
  const setImageStyleValue = React.useCallback((value) => {
    dispatch({
      type: "SET_IMAGE_STYLE_VALUE",
      payload: {
        value
      }
    });
    saveImageStyle(value);
  }, []);
  const submitPrompt = React.useCallback(
    async (prompt, imageStyle, options = { isDirty: false, isRetry: false }) => {
      const requestId = Date.now().toString();
      dispatch({
        type: "SUBMIT_PROMPT",
        payload: {
          requestId
        }
      });
      if (options.isRetry) {
        publishModalAction("retry_image_prompt", prompt, imageStyle);
      } else {
        publishModalAction(
          options.isDirty ? "free_image_prompt" : "image_prompt",
          prompt,
          imageStyle
        );
      }
      try {
        const response = await fetchImagePrompt({ prompt, imageStyle });
        switch (response.type) {
          case "ERROR":
            throw new Error(response.error);
          case "VALIDATION_ERROR":
            dispatch({
              type: "SET_VALIDATION_ERROR",
              payload: response.error
            });
            return;
          case "RATE_LIMIT_ERROR":
            dispatch({
              type: "SET_RATE_LIMIT_ERROR",
              payload: response.error
            });
            return;
          default:
            break;
        }
        const { url, blob } = response.results;
        const type = blob?.type?.split("/")?.[1] || "png";
        focusInputArea();
        dispatch({
          type: "FINISH_LOADING",
          payload: {
            file: new File(
              [blob],
              `generated_image_${Date.now()}.${type}`,
              blob?.type ? { type: blob.type } : void 0
            ),
            result: url,
            requestId
          }
        });
        focusInputArea();
      } catch {
        publishModalAction("image_prompt_error", prompt, imageStyle);
        dispatch({
          type: "SET_ERROR",
          payload: {
            requestPrompt: prompt,
            requestImageStyle: imageStyle
          }
        });
      }
    },
    [fetchImagePrompt]
  );
  const insertImage = React.useCallback(
    async (entry, position) => {
      if (isOfType(["GENERATING"], entry)) {
        return;
      }
      adapter.tiptapEditor.commands.insertImageFromFile(entry.file, position, getPublicCommands());
      publishModalAction(`insert-${position}`);
      return true;
    },
    [adapter]
  );
  const tryConvertingSelectionToPrompt = React.useCallback(
    async (selection) => {
      const requestId = Date.now().toString();
      try {
        dispatch({
          type: "INITIALIZE",
          payload: {
            requestId
          }
        });
        const response = await fetchPromptFromSelection({ selection });
        if (response.type === "ERROR" || response.type === "VALIDATION_ERROR" || response.type === "RATE_LIMIT_ERROR") {
          throw new Error(response.error);
        }
        publishModalAction(`convert_text_to_prompt`, response.results[0]);
        focusInputArea();
        dispatch({
          type: "DONE_INITIALIZE",
          payload: {
            value: response.results[0],
            requestId
          }
        });
        setConvertedPromptHelperVisible(savedConvertedPromptHelperValue);
        focusInputArea();
      } catch {
        publishModalAction(`convert_text_to_prompt_error`);
        dispatch({
          type: "DONE_INITIALIZE",
          payload: {
            value: selection,
            requestId
          }
        });
        setConvertedPromptHelperVisible(false);
      }
    },
    [fetchPromptFromSelection]
  );
  const cancelPrompt = React.useCallback(() => {
    if (state.type === "IN_PROGRESS") {
      focusInputArea();
    }
    publishModalAction("cancel_image_prompt");
    dispatch({
      type: "CANCEL_PROMPT"
    });
  }, [state]);
  const retryPrompt = React.useCallback(() => {
    if (!isOfType(["ERROR"], state)) {
      return;
    }
    return submitPrompt(state.requestPrompt, state.requestImageStyle, {
      isDirty: state.isDirty,
      isRetry: true
    });
  }, [state, submitPrompt]);
  const goBack = React.useCallback(() => {
    dispatch({
      type: "GO_BACK"
    });
  }, [state]);
  return {
    setPromptValue,
    tryConvertingSelectionToPrompt,
    setImageStyleValue,
    insertImage,
    submitPrompt,
    cancelPrompt,
    retryPrompt,
    goBack
  };
};
export {
  useAiImageModalActions
};
//# sourceMappingURL=use-ai-image-modal-actions.js.map
