%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                   %
%      Made by Gabriel Ruprecht     %
%                                   %
% This work is published under the  %
% LaTeX project public license 1.3  %
%                                   %
%       Package version 1.1.0       %
%            2025-01-20             %
%                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ProvidesPackage{printliederbuch}[version 1.1.0]

\RequirePackage{liederbuch}
\RequirePackage{hyperref}

\listofsongsstyle{simple with number}

\ExplSyntaxOn


\newcommand{\printLiederbuch}[1]{
% Select the highest toc level
% depending on the document class
\ifx\chapter\undefined
\section{#1}
\else
\chapter{#1}
\fi
  \fbox
   {
   % Print songbook metadata
    \begin{tabular}{l l}
    Meta ~ data ~ name & Meta ~ data ~ value ~ \\
    \hline
    \tl_use:N \csuse{liederbuchMeta;#1}
    \end{tabular}
   }%fbox

\csuse{liederbuchBody;#1}
}


\RenewEnviron{liederbuch}[2][]{
  \gdef\equals{=}
  \xdef\GFM@LB@songbook{#2}
  \global\cslet{liederbuchBody;#2}\BODY
  \tl_set:Nn \l_tmpa_tl { #1 }
  \tl_replace_all:Nnn \l_tmpa_tl { & } { \\ }
  \tl_replace_all:Nnn \l_tmpa_tl { = } { & }
  \global\cslet{liederbuchMeta;#2}\l_tmpa_tl
}


\NewDocumentEnvironment{lied}{O{}mm +b}
 {
    %Meta data unboxing is necessary to fill the listofsongs with content:
    \def\GFM@LB@number{#2}%
    \def\GFM@LB@variant{#3}%
    \edef\GFM@LB@expandedName{GFM@LB@lied@\GFM@LB@songbook @\GFM@LB@variant @\GFM@LB@number}%
    \GFM@LB@unpackage{#1}%
    \def\GFM@LB@number{#3}%
    \def\GFM@LB@variant{#2}%
    
    % Select the second highest toc level
    % depending on the document class
    \ifx\chapter\undefined
        \subsection{#3\ --\ Variant:\ #2}
    \else
        \section{#3\ --\ Variant:\ #2}
    \fi
    
    % Print song metadata
    \tl_set:Nn \l_tmpa_tl { #1 }
    \tl_replace_all:Nnn \l_tmpa_tl { & } { \\ }
    \tl_replace_all:Nnn \l_tmpa_tl { = } { & }
    \fbox
    {
        \begin{tabular}{l l}
            Meta ~ data ~ name & Meta ~ data ~ value ~ \\
            \hline
            \tl_use:N \l_tmpa_tl
        \end{tabular}
    }%fbox
    
    % list of songs:
    \xdef\@currentlabelname{\csname \GFM@LB@expandedName @title\endcsname}
    \refstepcounter{liedcounter}
    \addcontentsline{los}{song}{
    \expandafter\ifx\csname \GFM@LB@expandedName @title\endcsname\relax
    $<$ ~ No ~ title ~ $>$
    \else
    \csname \GFM@LB@expandedName @title\endcsname
    \fi
    }
    
    % Actual content
    \par#4\par
}{}


\ExplSyntaxOff