\ProvidesPackage{mqperiodictable}
\RequirePackage{mqtranslation}
\RequirePackage{mqlua}
% 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
        % \detokenize{\label{el:#1}}
        \directlua{ 
            if elements["#1"]["labeled"] == nil then
                elements["#1"]["labeled"] = true
                tex.print("\\phantomsection\\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{fg3}{\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               = "bg-blue!50!bg0",
        metalloid           = "fg-orange!50!bg0",
        transitionmetal     = "fg-blue!50!bg0",
        lanthanoide         = "bg-orange!50!bg0",
        alkalimetal         = "fg-red!50!bg0",
        alkalineearthmetal  = "fg-purple!50!bg0",
        nonmetal            = "fg-aqua!50!bg0",
        halogen             = "fg-yellow!50!bg0",
        noblegas            = "bg-purple!50!bg0"
    }
}
\directlua{
    function getColor(cat) 
        local color = category2color[cat]
        if color == nil then
            return "bg3"
        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,fg-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}
}
