% use this to define text in different languages for the key <env arg>
% the translation for <env arg> when the environment ends.
% (temporarily change fqname to the \fqname:<env arg> to allow
% the use of \eng and \ger without the key parameter)
% [1]: key
\newenvironment{ttext}[1][desc]{
    \edef\realfqname{\fqname}
    \edef\fqname{\fqname:#1}
}{
    \expandafter\GT\expandafter{\fqname}% \\
    \edef\fqname{\realfqname}
}


\def\descwidth{0.3\textwidth}
\def\eqwidth{0.6\textwidth}


%
% FORMULA ENVIRONMENT
% The following commands are meant to be used with the formula environment
%

% Name in black and below description in gray
% [1]: minipage width
% 2: fqname of name
% 3: fqname of a translation that holds the explanation
\newcommand{\NameWithExplanation}[3][\descwidth]{
    \begin{minipage}{#1}
        \IfTranslationExists{#2}{
            \raggedright
            \GT{#2}
        }{NO NAME} 
        \IfTranslationExists{#3}{
           \\ {\color{dark1} \GT{#3}}
        }{}
    \end{minipage}
}

% [1]: minipage width
% 2: content
% 3: fqname of a translation that holds the explanation
\newcommand{\ContentBoxWithExplanation}[3][\eqwidth]{
    \fbox{
    \begin{minipage}{#1}
        % \vspace{-\baselineskip}  % remove the space that comes from starting a new paragraph
        #2
        \noindent\IfTranslationExists{#3}{
            \begingroup
                \color{dark1} 
                \GT{#3}
                % \edef\temp{\GT{#1_defs}}
                % \expandafter\StrSubstitute\expandafter{\temp}{:}{\\}
            \endgroup
        }{}
        % \vspace{-\baselineskip}  % remove the space that comes from starting a new paragraph
    \end{minipage}
    }

}

% 1: fqname, optional with #1_defs and #1_desc defined
% 2: content
\newcommand{\NameLeftContentRight}[2]{
    \par\noindent\ignorespaces
    % \textcolor{gray}{\hrule}
    \vspace{0.5\baselineskip}
    \NameWithExplanation[\descwidth]{#1}{#1_desc}
    \hfill
    \ContentBoxWithExplanation[\eqwidth]{#2}{#1_defs}
    \textcolor{dark3}{\hrule}
    \vspace{0.5\baselineskip}
    % \par
    % \hrule
}

\newcommand{\insertEquation}[2]{
    \NameLeftContentRight{\fqname:#1}{
        \begin{align}
            \label{eq:\fqname:#1}
            #2
        \end{align}
    }
}

\newcommand{\insertFLAlign}[2]{  % eq name, #cols, eq
    \NameLeftContentRight{\fqname:#1}{%
        \begin{flalign}%
            % dont place label when one is provided
            % \IfSubStringInString{label}\unexpanded{#3}{}{
            %     \label{eq:#1}
            % }
            #2%
        \end{flalign}
    }
}

\newcommand{\insertAlignedAt}[3]{  % eq name, #cols, eq
    \NameLeftContentRight{\fqname:#1}{%
        \begin{alignat}{#2}%
            % dont place label when one is provided
            % \IfSubStringInString{label}\unexpanded{#3}{}{
            %     \label{eq:#1}
            % }
            #3%
        \end{alignat}
    }
}

\newcommand\luaexpr[1]{\directlua{tex.sprint(#1)}}
% [1]: width
% 2: fqname
% 3: file path
% 4: equation
\newcommand{\insertEquationWithFigure}[4][0.55]{
    \par\noindent\ignorespaces
    % \textcolor{gray}{\hrule}
    \vspace{0.5\baselineskip}
    \begin{minipage}{#1\textwidth}
        \NameWithExplanation[\textwidth]{\fqname:#2}{#2_desc}
        % TODO: why is this ignored
        \vspace{1.0cm}
        % TODO: fix box is too large without 0.9
        \ContentBoxWithExplanation[0.90\textwidth]{
            \begin{align}
                \label{eq:\fqname:#2}
                #4
            \end{align}
        }{#2_defs}
    \end{minipage}
    \hfill
    \begin{minipage}{\luaexpr{1.0-#1}\textwidth}
        \begin{figure}[H]
            \centering
            \includegraphics[width=\textwidth]{#3}
            \label{fig:\fqname:#2}
        \end{figure}
    \end{minipage}
    \textcolor{dark3}{\hrule}
    \vspace{0.5\baselineskip}

}

% 1: key
\newenvironment{formula}[1]{
    % [1]: language
    % 2: name
    % 3: description
    % 4: definitions/links
    \newcommand{\desc}[4][english]{
        % language, name, description, definitions
        \ifblank{##2}{}{\dt[#1]{##1}{##2}}
        \ifblank{##3}{}{\dt[#1_desc]{##1}{##3}}
        \ifblank{##4}{}{\dt[#1_defs]{##1}{##4}}
    }
    % 1: equation for align environment
    \newcommand{\eq}[1]{
        \insertEquation{#1}{##1}
    }
    % 1: equation for alignat environment
    \newcommand{\eqAlignedAt}[2]{
        \insertAlignedAt{#1}{##1}{##2}
    }
    % 1: equation for flalign environment
    \newcommand{\eqFLAlign}[1]{
        \insertFLAlign{#1}{##1}
    }
    % 1: file path
    % 2: equation
    \newcommand{\figeq}[2]{
        \insertEquationWithFigure{#1}{##1}{##2}
    }
    % 1: any content
    \newcommand{\content}[1]{
        \NameLeftContentRight{\fqname:#1}{##1}
    }
    % 1: content for the ttext environment
    \newcommand{\ttxt}[1]{
        \NameLeftContentRight{\fqname:#1}{
            \begin{ttext}[#1:desc]
                ##1
            \end{ttext}
        }
    }

}{\ignorespacesafterend}


%
% QUANTITY
%

% units: siunitx units arguments, possibly chained by '='
% returns: 1\si{unit1} = 1\si{unit2} = ...
\directlua{
    function split_and_print_units(units)
        if units == nil then
            tex.print("1")
            return
        end
            
        local parts = {}
        for part in string.gmatch(units, "[^=]+") do
            table.insert(parts, part)
        end
        local result = ""
        for i, unit in ipairs(parts) do
            if i > 1 then result = result .. " = " end
            result = result .. "\\SI{1}{" .. unit .. "}"
        end
        tex.print(result)
    end
}

% 1: key
% 2: symbol
% 3: value
% 4: units
% 5: exp or def
% \newenvironment{constant}[5]{
%     % key, symbol, si unit(s), comment (key to global translation)
%     \newcommand{\desc}[3][english]{
%         % language, name, description
%         % \DT[qty:#1]{##1}{##2}
%         % \ifblank{##3}{}{\DT[qty:#1_desc]{##1}{##3}}
%         \ifblank{##2}{}{\DT[const:#1]{##1}{##2}}
%         \ifblank{##3}{}{\DT[const:#1_desc]{##1}{##3}}
%     }
%     % TODO put these in long term key - value storage for generating a full table and global referenes \constRef
%     % for references, there needs to be a label somwhere
%     \edef\constName{const:#1}
%     \edef\constDesc{const:#1_desc}
%     \def\constSymbol{#2}
%     \edef\constValue{#3}
%     \def\constUnits{#4}
%     \edef\constExpOrDef{const:#5}
% }
% {
%     \NameLeftContentRight{\constName}{
%         \begingroup
%             Symbol: $\constSymbol$
%             \IfTranslationExists{\constDesc}{
%                 \\Description: \GT{\constDesc}
%             }{}
%             \\Value: $\constValue$
%             \\Unit: $\directlua{split_and_print_units([[\constUnits]])}$
%             \GT{\constExpOrDef}
%             \label{\constName}
%         \endgroup
%     }
%     \ignorespacesafterend

%     % for TOC
%     \refstepcounter{constant}%
%     % \addquantity{\expandafter\gt\expandafter{\qtyname}}%
%     % \noindent\textbf{My Environment \themyenv: #1}\par%
% }
\newcounter{constant}
\newenvironment{constant}[3]{
    % [1]: language
    % 2: name
    % 3: description
    % 4: definitions/links
    \newcommand{\desc}[4][english]{
        % language, name, description, definitions
        \ifblank{##2}{}{\DT[const:#1]{##1}{##2}}
        \ifblank{##3}{}{\DT[const:#1_desc]{##1}{##3}}
        \ifblank{##4}{}{\DT[const:#1_defs]{##1}{##4}}
    }
    \directlua{
        constVals = {}
        constUnits = {}
    }
    % 1: equation for align environment
    \newcommand{\val}[2]{
        \directlua{
            %--table.insert(constVals, "LOL")
            table.insert(constVals, [[##1]])
            table.insert(constUnits, [[##2]])
            %--table.insert(constUnits, "\luaescapestring{##2}")
        }
        \def\constValue{##1}
        \def\constUnit{##2}
    }
    \edef\constName{const:#1}
    \edef\constDesc{const:#1_desc}
    \def\constSymbol{#2}
    \edef\constExpOrDef{\GT{const:#3}}
}{
    \NameLeftContentRight{\constName}{
        \begingroup  % for label
            Symbol: $\constSymbol$
            \IfTranslationExists{\constDesc}{
                \\Description: \GT{\constDesc}
            }{}
            % TODO manage multiple values
            % \\Value: $\constValue\,\si{\constUnit}$
            \\\constExpOrDef:
            \directlua{
                %--tex.sprint("Hier steht Luatext" .. ":", #constVals)
                for i, v in ipairs(constVals) do
                tex.sprint("\\\\\\hspace*{1cm}${", constVals[i], "}\\,\\si{", constUnits[i], "}$")
                    %--tex.sprint("VALUE ", i, v)
                end
            }
            \label{\constName}
        \endgroup
    }
    \ignorespacesafterend
}



% 1: key
% 2: symbol
% 3: units
% 4: comment key to translation
\newenvironment{quantity}[4]{
    % language, name, description
    \newcommand{\desc}[3][english]{
        \ifblank{##2}{}{\DT[qty:#1]{##1}{##2}}
        \ifblank{##3}{}{\DT[qty:#1_desc]{##1}{##3}}
    }
    % TODO put these in long term key - value storage for generating a full table and global referenes \qtyRef
    % for references, there needs to be a label somwhere
    \edef\qtyname{qty:#1}
    \edef\qtydesc{qty:#1_desc}
    \def\qtysymbol{#2}
    \def\qtyunits{#3}
    \edef\qtycomment{#4}
    % Unit: $\directlua{split_and_print_units([[\m\per\kg]])}$
}
{
    \NameLeftContentRight{\qtyname}{
        \begingroup
            Symbol: $\qtysymbol$
            \IfTranslationExists{\qtydesc}{
                \\Description: \GT{\qtydesc}
            }{}
            \\Unit: $\directlua{split_and_print_units([[\qtyunits]])}$
            \expandafter\IfTranslationExists\expandafter\qtycomment{
                \\Comment: \GT\qtycomment
            }{}%{\\No comment \color{gray}}
            \label{\qtyname}
        \endgroup
    }
    \ignorespacesafterend

    % for TOC
    \refstepcounter{quantity}%
    % \addquantity{\expandafter\gt\expandafter{\qtyname}}%
    % \noindent\textbf{My Environment \themyenv: #1}\par%
}
\newcounter{quantity}
\newcommand{\listofquantities}{%
    \section*{\GT{list_of_quantitites}}%
    \addcontentsline{toc}{section}{\GT{list_of_quantitites}}%
    \par\noindent\hrule\par\vspace{0.5\baselineskip}\@starttoc{myenv}%
}
\newcommand{\addquantity}[1]{\addcontentsline{quantity}{subsection}{\protect\numberline{\themyenv}#1}}

% Custon environment with table of contents, requires etoolbox?
% Define a custom list
\newcommand{\listofmyenv}{%
    \section*{List of My Environments}%
    \addcontentsline{toc}{section}{List of My Environments}%
    \par\noindent\hrule\par\vspace{0.5\baselineskip}\@starttoc{myenv}%
}
\newcommand{\addmyenv}[1]{\addcontentsline{myenv}{subsection}{\protect\numberline{\themyenv}#1}}
% Define the custom environment
\newcounter{myenv}
\newenvironment{myenv}[1]{%
  \refstepcounter{myenv}%
  \addmyenv{#1}%
  \noindent\textbf{My Environment \themyenv: #1}\par%
}{\par\vspace{0.5\baselineskip}}




%
% DISTRIBUTION
%
\def\distrightwidth{0.45\textwidth}
\def\distleftwidth{0.45\textwidth}

% Table for distributions
% create entries for parameters using \disteq
\newenvironment{distribution}{
    % 1: param name (translation key)
    % 2: math
    \newcommand{\disteq}[2]{
        % add links to some names
        \directlua{
            local cases = {
                pdf         = "eq:pt:distributions:pdf",
                pmf         = "eq:pt:distributions:pmf",
                cdf         = "eq:pt:distributions:cdf",
                mean        = "eq:pt:mean",
                variance    = "eq:pt:variance"
            }
            if cases["\luaescapestring{##1}"] \string~= nil then
                tex.sprint("\\hyperref["..cases["\luaescapestring{##1}"].."]{\\GT{##1}}")
            else
                tex.sprint("\\GT{##1}")
            end
        }
        & ##2 \\ \hline
    }
    \hfill
    \begin{minipage}{\distrightwidth}
        \begingroup
            \setlength{\tabcolsep}{0.9em}  % horizontal
            \renewcommand{\arraystretch}{2}  % vertical
            \begin{tabular}{|l|>{$\displaystyle}c<{$}|}
            \hline
}{
            \end{tabular}
        \endgroup
    \end{minipage}
}

% A 2 column table in a minipage
% create entries for parameters using \entry
% 1: minipage width
% 2: key of the table
\newenvironment{minipagetable}[2][0.5\textwidth]{
    % save real fq name
    \edef\tmpFqname{\fqname}
    \edef\tmpMinipagetableWidth{#1}
    \edef\tmpMinipagetableName{#2}
    \directlua{
        entries = {}
    }

    % 1: field name (translation key)
    % 2: translation define statements (field content)
    \newcommand{\entry}[2]{
        % temporarily set fqname so that the translation commands dont need an explicit key
        \edef\fqname{\tmpFqname:#2:##1}
        ##2
        \edef\fqname{\tmpFqname}
        \directlua{
            table.insert(entries, "\luaescapestring{##1}")
        }
    }
}{
    % \hfill
    \begin{minipage}{\tmpMinipagetableWidth}
        \begingroup
            \setlength{\tabcolsep}{0.9em}  % horizontal
            \renewcommand{\arraystretch}{2}  % vertical
            \begin{tabularx}{\textwidth}{|l|X|}
            \hline
            \directlua{
                for _, k in ipairs(entries) do
                    tex.print("\\GT{" .. k .. "} & \\gt{\tmpMinipagetableName:" .. k .. "}\\\\")
                end
            }
            \hline
            \end{tabularx}
        \endgroup
    \end{minipage}
    % reset the fqname
}
