import { useEffect, useState } from "react";
import { OverlaysObserver } from "./OverlayObserver/OverlaysObserver";
import { useFeedLoader } from "../../reactHooks";
import { usePlayer } from "./usePlayer";

const getLiveUrl = (url: string) => {
  // Use the replace method with a regular expression to replace all instances of subClass with livePage
  return url.replace(new RegExp("subClass", "g"), "livePage");
};

export const useTitleSummaryOverlay = (
  entry,
  isLive = false,
  interval: number
) => {
  // TODO: Have generic place for live url from configuration. Currently its hardcoded for client.
  const feedUrl = getLiveUrl(entry?.extensions?.live?.channel_src ?? "");
  const player = usePlayer();
  const [title, setTitle] = useState<string | number>(entry?.title || "");
  const [summary, setSummary] = useState<string | number>(entry?.summary || "");

  // Hook to load feed data
  const { data: feedData, reloadData } = useFeedLoader({ feedUrl });

  useEffect(() => {
    if (player && feedUrl && isLive) {
      const observer = new OverlaysObserver({ player });

      observer.setFeedDataHandlers(feedUrl, reloadData, interval, (entry) => {
        setTitle(entry?.title || "");
        setSummary(entry?.summary || "");
      });

      const subscription = observer
        .getTitleSummaryObservable()
        .subscribe(({ title, summary }) => {
          setTitle(title);
          setSummary(summary);
        });

      return () => {
        subscription.unsubscribe();
        observer.clearFeedDataInterval();
      };
    }
  }, [player, feedUrl, reloadData, isLive]);

  useEffect(() => {
    if (isLive && feedData?.entry?.[0]) {
      setTitle(feedData.entry[0].title || "");
      setSummary(feedData.entry[0].summary || "");
    }
  }, [feedData]);

  return { title, summary };
};
