import { useEffect, useRef } from "react";
import { cacheService } from "../services";

export const useAutoSave = (content: string, username: string, cacheKey: string | undefined) => {
  const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  useEffect(() => {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      const key = cacheService.key(username, cacheKey);
      cacheService.save(key, content);
    }, 300);
    return () => clearTimeout(timerRef.current);
  }, [content, username, cacheKey]);
};
