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

export const useAuth = (navigation) => {
    const auth = navigation.getParam('auth', { Access: false, Update: false, Delete: false, Business: false });
    const userinfo = navigation.getParam('userinfo', { BusinessFieldId: 0, Name: '', SiteId: 0, SiteName: '', UserGroupId: 0, UserId: '' });
    const sitemap = navigation.getParam('sitemap', { name: '', auth: {}, path: '', icon: '', id: 0, parentid: 0 });
    const config = navigation.getParam('config', {});
    return { auth, userinfo, sitemap, config };
};

export const usePrevious = (value) => {
    const ref = useRef();
    useEffect(() => {
        ref.current = value;
    }, [value]);
    return ref.current;
};

export const useLayout = () => {
    const ref = useRef(null);
    const [layout, setLayout] = useState(null);
    const [measure, setMeasure] = useState(null);
    const complete = useRef(false);
    const result = useRef({
        ref: null,
        layout: null,
        measure: null,
        onLayout: (event) => {},
        isComplete: () => {
            return false;
        },
        updateMeasure: updateMeasure,
    });
    const completeTimer = useRef(null);

    result.current.ref = ref;
    result.current.layout = layout;
    result.current.measure = measure;
    result.current.onLayout = (event) => {
        console.log('onlayout');
        const currlayout = { ...event.nativeEvent.layout };
        setLayout(currlayout);
        updateMeasure();
    };
    result.current.isComplete = () => {
        return complete.current;
    };
    result.current.updateMeasure = updateMeasure;

    const updateMeasure = () => {
        console.log('update measure');
        if (result.current.ref?.current?.measure) {
            console.log('has measure');
            result.current.ref.current.measure((x, y, width, height, pageX, pageY) => {
                console.log('measure...');
                if (
                    measure?.x != x ||
                    measure?.y != y ||
                    measure?.pageX != pageX ||
                    measure?.pageY != pageY ||
                    measure?.width != width ||
                    measure?.height != height
                ) {
                    complete.current = false;
                    setMeasure({ x, y, width, height, pageX, pageY });
                } else {
                    complete.current = true;
                }
            });
        }
    };

    useEffect(() => {
        updateMeasure();
    }, [result.current.ref.current]);

    updateMeasure();

    return result.current;
};
