\ProvidesPackage{mqfqname}
\RequirePackage{mqlua}
\RequirePackage{etoolbox}


\begin{luacode}
    sections = sections or {}

    function fqnameEnter(name)
        table.insert(sections, name)
        -- table.sort(sections)
    end

    function fqnameLeave()
        if table.getn(sections) > 0 then
            table.remove(sections)
        end
    end

    function fqnameGet()
        return table.concat(sections, ":")
    end

    function fqnameLeaveOnlyFirstN(n)
        if n >= 0 then
            while table.getn(sections) > n do
                table.remove(sections)
            end
        end
    end
\end{luacode}

\begin{luacode}
    function fqnameGetDepth()
        return table.getn(sections)
    end

    function fqnameGetN(N)
        if N == nil or table.getn(sections) < N then
            luatexbase.module_warning('fqnameGetN', 'N = ' .. N .. ' is larger then the table length')
            return "?!?"
        end
        s = sections[1]
        for i = 2, N do
            s = s .. ":" .. sections[i]
        end
        return s
    end
\end{luacode}

\newcommand{\mqfqname@update}{%
    \edef\fqname{\luavar{fqnameGet()}}
}
\newcommand{\mqfqname@enter}[1]{%
    \directlua{fqnameEnter("\luaescapestring{#1}")}%
    \mqfqname@update
}
\newcommand{\mqfqname@leave}{%
    \directlua{fqnameLeave()}%
    \mqfqname@update
}

\newcommand{\mqfqname@leaveOnlyFirstN}[1]{%
    \directlua{fqnameLeaveOnlyFirstN(#1)}%
}

% SECTIONING
% start <section>, get heading from translation, set label
% fqname is the fully qualified name of all sections and formulas, the keys of all previous sections joined with a ':'
% fqname is secFqname:<key> where <key> is the key/id of some environment, like formula
% [1]: code to run after setting \fqname, but before the \part, \section etc
% 2: key
\newcommand{\Part}[2][desc]{
    \newpage
    \mqfqname@leaveOnlyFirstN{0}
    \mqfqname@enter{#2}
    #1
    % this is necessary so that \part/\section... takes the fully expanded string. Otherwise the pdf toc will have just the fqname
    \edef\fqnameText{\GT{\fqname}}
    \part{\fqnameText} 
    \mqfqname@label
}
\newcommand{\Section}[2][]{
    \mqfqname@leaveOnlyFirstN{1}
    \mqfqname@enter{#2}
    #1
    \edef\fqnameText{\GT{\fqname}}
    \section{\fqnameText}
    \mqfqname@label
}
\newcommand{\Subsection}[2][]{
    \mqfqname@leaveOnlyFirstN{2}
    \mqfqname@enter{#2}
    #1
    \edef\fqnameText{\GT{\fqname}}
    \subsection{\fqnameText}
    \mqfqname@label
}
\newcommand{\Subsubsection}[2][]{
    \mqfqname@leaveOnlyFirstN{3}
    \mqfqname@enter{#2}
    #1
    \edef\fqnameText{\GT{\fqname}}
    \subsubsection{\fqnameText}
    \mqfqname@label
}
\edef\fqname{NULL}

\newcommand\printFqName{\expandafter\detokenize\expandafter{\fqname}}
