% Store info about elements in a lua table
% Print as list or as periodic table
% The data is taken from https://pse-info.de/de/data as json and parsed by the scripts/periodic_table.py

% INFO
\directLuaAux{
    if elements == nil then
        elements = {}       %-- Symbol: {symbol, atomic_number, properties, ... }
        elementsOrder = {}  %-- Number: Symbol
    end
}

% 1: symbol
% 2: nr
% 3: period
% 4: column
\newenvironment{element}[4]{
    % [1]: language
    % 2: name
    % 3: description
    % 4: definitions/links
    \newcommand{\desc}[4][english]{
        % language, name, description, definitions
        \ifblank{##2}{}{\DT[el:#1]{##1}{##2}}
        \ifblank{##3}{}{\DT[el:#1_desc]{##1}{##3}}
        \ifblank{##4}{}{\DT[el:#1_defs]{##1}{##4}}
    }
    \directLuaAux{
        elementsOrder[#2] = "#1";
        elements["#1"] = {};
        elements["#1"]["symbol"]  = [[\detokenize{#1}]];
        elements["#1"]["atomic_number"]  = [[\detokenize{#2}]];
        elements["#1"]["period"]  = [[\detokenize{#3}]];
        elements["#1"]["column"]  = [[\detokenize{#4}]];
        elements["#1"]["properties"]  = {};
    }
    % 1: key
    % 2: value
    \newcommand{\property}[2]{
        \directlua{  %-- writing to aux is only needed for references for now
            elements["#1"]["properties"]["##1"] = "\luaescapestring{\detokenize{##2}}" %-- cant use [[ ]] because electron_config ends with ]
        }
    }
    \edef\lastElementName{#1}
}{
    % \expandafter\printElement{\lastElementName}
    \ignorespacesafterend
}

% LIST
\newcommand\printElement[1]{
    \edef\elementName{el:#1}
    \par\noindent\ignorespaces
    \vspace{0.5\baselineskip}
    \begingroup
        % label it only once
        \directlua{ 
            if elements["#1"]["labeled"] == nil then
                elements["#1"]["labeled"] = true
                tex.print("\\label{el:#1}")
            end
        }
        \NameWithDescription[\descwidth]{\elementName}{\elementName_desc}
        \hfill
        \begin{ContentBoxWithExplanation}{\elementName_defs}
            \directlua{
                tex.sprint("Symbol: \\ce{"..elements["#1"]["symbol"].."}")
                tex.sprint("\\\\Number: "..elements["#1"]["atomic_number"])
            }
            \directlua{
                %--tex.sprint("Hier steht Luatext" .. ":", #elementVals)
                for key, value in pairs(elements["#1"]["properties"]) do
                    tex.sprint("\\\\\\hspace*{1cm}{\\GT{", key, "}: ", value, "}")
                    %--tex.sprint("VALUE ", i, v)
                end
            }
        \end{ContentBoxWithExplanation}
    \endgroup
    \textcolor{dark3}{\hrule}
    \vspace{0.5\baselineskip}
    \ignorespacesafterend
}
\newcommand{\printAllElements}{
    \directlua{
            %-- tex.sprint("\\printElement{"..val.."}")
        for key, val in ipairs(elementsOrder) do
            %-- tex.sprint(key, val);
            tex.print("\\printElement{"..val.."}")
        end
    }
}

% PERIODIC TABLE
\directlua{
    category2color = {
        metal               = "neutral_blue",
        metalloid           = "bright_orange",
        transitionmetal     = "bright_blue",
        lanthanoide         = "neutral_orange",
        alkalimetal         = "bright_red",
        alkalineearthmetal  = "bright_purple",
        nonmetal            = "bright_aqua",
        halogen             = "bright_yellow",
        noblegas            = "neutral_purple"
    }
}
\directlua{
    function getColor(cat) 
        local color = category2color[cat]
        if color == nil then
            return "light3"
        else
            return color
        end
    end
}
\newcommand{\drawPeriodicTable}{
    \def\ptableUnit{0.90cm}
    \begin{tikzpicture}[
        element/.style={anchor=north west, draw, minimum width=\ptableUnit, minimum height=\ptableUnit, align=center},
        element_annotation/.style={anchor=north west, font=\tiny, inner sep=1pt},
        x=\ptableUnit,
        y=\ptableUnit
    ]
    \directlua{
        for k, v in pairs(elements) do
            local column = tonumber(v.column)
            local period = tonumber(v.period)
            if 5 < period and 4 <= column and column <= 17 then
                period = period + 3
            elseif column > 17 then
                column = column - 14
            end
            tex.print("\\node[element,fill=".. getColor(v.properties.set) .."] at (".. column ..", -".. period ..") {\\elRef{".. v.symbol .."}};")
            tex.print("\\node[element_annotation] at (".. column ..", -".. period ..") {".. v.atomic_number .."};")
            if v.properties.atomic_mass \string~= nil then
                tex.print("\\node[element_annotation,anchor=south west] at (".. column ..", -".. period+1 ..") {".. string.format("\percentchar .3f", v.properties.atomic_mass) .."};")
            end
        end
    }
    \draw[ultra thick,faded_purple] (4,-6) -- (4,-11);
    % color legend for categories
    \directlua{
        local x0 = 4
        local y0 = -1
        local x = 0
        local y = 0
        local ystep = 0.4
        for set, color in pairs(category2color) do
        %-- tex.print("\\draw[fill=".. color .."] ("..x0+x..","..y0+y..") rectangle ("..x0+x..","..y0+y..")()")
            tex.print("\\node[anchor=west, align=left] at ("..x0+x..","..y0-y..") {{\\color{".. color .."}\\blacksquare} \\GT{".. set .."}};")
            y = y + 1*ystep
            if y > 4*ystep then
                y = 0
                x = x+4
            end
        end
    }
    % period numbers
    \directlua{
        for i = 1, 7 do
            tex.print("\\node[anchor=east,align=right] at (1,".. -i-0.5 ..") {".. i .."};")
        end
    }
    \end{tikzpicture}



}
