"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const enums_1 = require("../enums");
const useLogic = ({ jsonData }) => {
    const [data, setData] = (0, react_1.useState)(null);
    const [expandedKeys, setExpandedKeys] = (0, react_1.useState)(new Set());
    const [copyStatus, setCopyStatus] = (0, react_1.useState)(enums_1.CopyStatus.CanCopy);
    const collapseAll = () => {
        setExpandedKeys(new Set());
    };
    const checkExpanded = (key) => {
        return expandedKeys.has(key);
    };
    const expandAll = () => {
        const newExpandedKeys = new Set();
        const collectKeys = (obj, prefix = '') => {
            if (typeof obj === 'object' && obj !== null) {
                if (Array.isArray(obj)) {
                    obj.forEach((item, index) => {
                        const fullKey = prefix ? `${prefix}.${index}` : String(index);
                        newExpandedKeys.add(fullKey);
                        collectKeys(item, fullKey);
                    });
                }
                else {
                    Object.keys(obj).forEach((key) => {
                        const fullKey = prefix ? `${prefix}.${key}` : key;
                        newExpandedKeys.add(fullKey);
                        collectKeys(obj[key], fullKey);
                    });
                }
            }
        };
        collectKeys(data);
        setExpandedKeys(newExpandedKeys);
    };
    const copyAll = () => {
        navigator.clipboard
            .writeText(JSON.stringify(data))
            .then(() => {
            setCopyStatus(enums_1.CopyStatus.Copied);
        })
            .catch(() => {
            setCopyStatus(enums_1.CopyStatus.Error);
        });
        setTimeout(() => {
            setCopyStatus(enums_1.CopyStatus.CanCopy);
        }, 2000);
    };
    const toggleExpanded = (key) => {
        const newExpandedKeys = new Set(expandedKeys);
        if (newExpandedKeys.has(key)) {
            newExpandedKeys.delete(key);
        }
        else {
            newExpandedKeys.add(key);
        }
        setExpandedKeys(newExpandedKeys);
    };
    (0, react_1.useEffect)(() => {
        try {
            setData(typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData);
        }
        catch (error) {
            throw new Error(`Error parsing JSON data: ${error}`);
        }
    }, [jsonData]);
    return {
        data,
        copyStatus,
        collapseAll,
        expandAll,
        copyAll,
        toggleExpanded,
        checkExpanded,
    };
};
exports.useLogic = useLogic;
