import {
  useEffect,
  useState,
} from 'react';

import { rpc } from '@/api/request';
import { SortDFInput } from '@/api/types';

type HashUpdateProps = {
    lock: boolean;
    collection?: string;
    limit?: number;
    offset?: number;
    search?: string | null;
    sort?: SortDFInput;
    stage?: string;
    currentHash?: string | null;
    filter: any;
    pipeline: any;
    onHashUpdate: () => void;
}

const HashUpdate = ({
    filter,
    lock, collection, limit, offset, search, sort, currentHash, onHashUpdate, pipeline }: HashUpdateProps) => {


    const [hashLoading, setHashLoading] = useState<boolean>(false);

    useEffect(() => {

        //Если это дев то выходим
        if (import.meta.env.DEV) return;


        if (lock) return;

        if (!collection) return;

        setHashLoading(false);


        const intervalHashUpdate = setInterval(() => {



            setHashLoading(true);
            rpc.hash({


                collection: collection,
                limit: limit,
                offset: offset,
                search: (!!search && !!search.trim()) ? search.trim() : undefined,
                sort: !!sort ? sort : undefined,
                filter: !!filter ? filter : undefined,
                pipeline: !!pipeline ? pipeline : undefined,
            }).then((newHash) => {

                if (!!newHash?.result && newHash.result !== currentHash) {

                    onHashUpdate();
                }
            }).catch((err) => {

            }).finally(() => {
                setHashLoading(false);
            });

        }, 5000);


        return () => {
            clearInterval(intervalHashUpdate);
        }


    }, [lock, collection, limit, offset, search, sort, filter, currentHash, onHashUpdate]);




    // return <Badge>{hashLoading ? 'Updating...' : 'Updated'}</Badge>
    return <></>

}

export default HashUpdate;