/**
 * WordPress dependencies
 */
import { decodeEntities } from '@wordpress/html-entities';

/**
 * Returns terms in a tree form.
 *
 * @since 3.16.0
 *
 * @param {Array} flatTerms Array of terms in flat format.
 *
 * @return {Array} Array of terms in tree format.
 */
export function buildTermsTree( flatTerms ) {
    const flatTermsWithParentAndChildren = flatTerms.map( ( term ) => {
        return {
            children: [],
            parent: null,
            ...term,
        };
    } );

    // All terms should have a `parent` because we're about to index them by it.
    if (
        flatTermsWithParentAndChildren.some( ( { parent } ) => parent === null )
    ) {
        return flatTermsWithParentAndChildren;
    }

    const termsByParent = flatTermsWithParentAndChildren.reduce(
        ( acc, term ) => {
            const { parent } = term;
            if ( ! acc[ parent ] ) {
                acc[ parent ] = [];
            }
            acc[ parent ].push( term );
            return acc;
        },
        {}
    );

    const fillWithChildren = ( terms ) => {
        return terms.map( ( term ) => {
            const children = termsByParent[ term.id ];
            return {
                ...term,
                children:
                    children && children.length
                        ? fillWithChildren( children )
                        : [],
            };
        } );
    };

    return fillWithChildren( termsByParent[ '0' ] || [] );
}

export const unescapeString = ( arg ) => {
    return decodeEntities( arg );
};

/**
 * Returns a term object with name unescaped.
 *
 * @since 3.16.0
 *
 * @param {Object} term The term object to unescape.
 *
 * @return {Object} Term object with name property unescaped.
 */
export const unescapeTerm = ( term ) => {
    return {
        ...term,
        name: unescapeString( term.name ),
    };
};

/**
 * Returns an array of term objects with names unescaped.
 * The unescape of each term is performed using the unescapeTerm function.
 *
 * @since 3.16.0
 *
 * @param {Object[]} terms Array of term objects to unescape.
 *
 * @return {Object[]} Array of term objects unescaped.
 */
export const unescapeTerms = ( terms ) => {
    return ( terms ?? [] ).map( unescapeTerm );
};
