'use client'

import { useCallback, useEffect, useRef } from 'react';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY } from '../../constants/common';
import { trackingStartSession } from '../sessions';

const DURATION = 30000;

export const useSessionTracking = (locale: string, sessionId: number) => {
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const timer = useRef<number>();

    const fetchData = useCallback(() => {
        trackingStartSession(locale, jwt, sessionId)
            .then(() => {
                console.log('tracking success');
            })
            .catch((err) => {
                console.log('tracking error', err);
            })
    }, []);

    useEffect(() => {
        return () => {
            window.clearInterval(timer.current);
        }
    }, []);

    const start = () => {
        window.clearInterval(timer.current);

        timer.current = window.setInterval(() => {
            fetchData();
        }, DURATION);
    };

    const stop = () => {
        window.clearInterval(timer.current);
    };

    return {
        start,
        stop
    };
};
