import React, { useCallback, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { ArticleStore } from "../domain/articleStore";
import type { Article } from "../domain/articleEntity";
import type { ArticleStoreState } from "../data/articleReducer";
import { getArticleAction, setArticleAction } from "./articleActions";
import { RootState, useAppSelector } from "store";

const articleSelector = (state: RootState): ArticleStoreState => state.article;

const useArticleStore = (): ArticleStore => {
  const { isLoading, article, hasError } = useAppSelector(articleSelector);

  const dispatch = useDispatch();

  const setArticle = useCallback(
    (article: Article) => setArticleAction(article)(dispatch),
    [dispatch]
  );

  const getArticle = useCallback(
    (id: string) => getArticleAction(id)(dispatch),
    [dispatch]
  );

  return {
    article: article,
    isLoading,
    hasError,
    setArticle,
    getArticle,
  };
};

export { useArticleStore };
