\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{upc-report}  %[2024-10-07 v1.0 UPC Report Template] based on [2023-05-31 v1.0 UPM Report Template]

\LoadClass[12pt,a4paper,oneside]{book}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Nos aseguramos de que usamos xetex como motor de compilación
%
\RequirePackage{ifxetex}
\RequireXeTeX

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Paquetes globales
%
\RequirePackage[titletoc]{appendix}  % Que aparezca "Apéndice"
\RequirePackage{awesomebox}  % Bloques de texto más molones
\RequirePackage{changepage}  % Para poder usar los adjustwidth
\RequirePackage[style=english]{csquotes} % Facilitar el trabajo con citas
\RequirePackage{eso-pic}  % Colores y fondos
\RequirePackage{graphicx}  % Mejoras sobre el paquete graphics
\RequirePackage{hologo}  % Para poner logos relacionados con LaTeX
\RequirePackage{ifthen}  % Para poder usar condicionales en la clase
\RequirePackage{pdflscape}  % Posibilidad de páginas en apaisado
\RequirePackage{xcolor}  % Mejoras sobre el paquete color
\RequirePackage{algorithm} % Permite añadir tablas de pseudocodigo y algoritmos
\RequirePackage{algpseudocode} % Permite escribir en notacion de pseudocodigo

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Valores constantes
% TODO: Adaptar text en idiomes dinamics.
\def\universityname{Universitat Politècnica de Catalunya}  
\def\universitysurname{BarcelonaTech (UPC)}  
\def\templaterepository{https://github.com/blazaid/upm-report-Template}
\def\originaltemplaterepository{https://github.com/blazaid/upm-report-Template}
% Deberiamos tanto de citar el template original, como subir al github el template resultante

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Opciones de la clase
%
\RequirePackage{kvoptions} % Para usar argumentos al importar la clase
\SetupKeyvalOptions{family=@upc, prefix=@upc@}

% Opciones de configuración de la clase
\DeclareStringOption{type}
\DeclareStringOption{school}
\DeclareStringOption{degree}
\DeclareStringOption{external}
\ProcessKeyvalOptions*

% Variables relacionadas con el tipo de memoria (arg. `type`)
\newcommand{\reporttype}{}
\newcommand{\reporttypeabbr}{}
\ifthenelse{\equal{\@upc@type}{pfg}}{
    \renewcommand{\reporttype}{Projecte Fi de Grau}
    \renewcommand{\reporttypeabbr}{PFG}
}{
\ifthenelse{\equal{\@upc@type}{tfg}}{
    \renewcommand{\reporttype}{Treball Fi de Grau}
    \renewcommand{\reporttypeabbr}{TFG}
}{
\ifthenelse{\equal{\@upc@type}{pfm}}{
    \renewcommand{\reporttype}{Projecte Fi de Màster}
    \renewcommand{\reporttypeabbr}{PFM}
}{
\ifthenelse{\equal{\@upc@type}{tfm}}{
    \renewcommand{\reporttype}{Treball Fi de Màster}
    \renewcommand{\reporttypeabbr}{TFM}
}{
\ifthenelse{\equal{\@upc@type}{td}}{
    \renewcommand{\reporttype}{Tesis Doctoral}
    \renewcommand{\reporttypeabbr}{PhD}
}{
\ifthenelse{\equal{\reporttype}{}}{
    \PackageError{upc-report}{Report type}{Falta el parámetro 'type'}
}{}}}}}}


% Variables relacionadas con la escuela (arg. `school`)
\newcommand{\schoolname}{ERROR: NO DEFINIDO}
\newcommand{\schoolabbr}{ERROR: NO DEFINIDO}
\newcommand{\schoollogo}{ERROR: NO DEFINIDO}
\newcommand{\schooladdress}{ERROR: NO DEFINIDO}
\newcommand{\degreecode}{ERROR: NO DEFINIDO}
\newcommand{\degreename}{ERROR: NO DEFINIDO}
\ifthenelse{\equal{\@upc@school}{fme}}{%
    % Datos de la escuela
    \renewcommand{\schoolname}{FME - Facultat de Matemàtiques i Estadística}
    \renewcommand{\schoolabbr}{FME}
    \renewcommand{\schoollogo}{upc-report/logos/upc/fme-logo-edited.png}
    \renewcommand{\schooladdress}{%
        Edifici U\\
        PAU GARGALLO, 14\\
        BARCELONA\\
        08028\\
        934015880\\
    }
    \definecolor{schoolcolor}{RGB}{00,119,200}
    \definecolor{linkcolor}{RGB}{00,119,200}
}{
\ifthenelse{\equal{\@upc@school}{etsiaab}}{%
    % Datos de la escuela
    \renewcommand{\schoolname}{E.T.S. de Ingeniería Agronómica, Alimentaria y de Biosistemas}
    \renewcommand{\schoolabbr}{ETSIAAB}
    \renewcommand{\schoollogo}{upc-report/logos/logo-etsiaab.png}
    \renewcommand{\schooladdress}{%
        Av. Puerta de Hierro, nº 2 - 4\\
        28040 Madrid, España
    }
    \definecolor{schoolcolor}{RGB}{99,178,76}
    \definecolor{linkcolor}{RGB}{99,178,76}
}
}

% Variables relacionadas con la titulación (arg. `degree`)

%% ETSAAB
\ifthenelse{\equal{\@upc@degree}{GM}}{
    \renewcommand{\degreecode}{GM}
    \renewcommand{\degreename}{Grau en Matemàtiques}
}{\ifthenelse{\equal{\@upc@degree}{GE}}{
    \renewcommand{\degreecode}{GE}
    \renewcommand{\degreename}{Grau en Estadística}
}{\ifthenelse{\equal{\@upc@degree}{MESIO}}{
    \renewcommand{\degreecode}{MESIO}
    \renewcommand{\degreename}{Master en estadistica}
}{\ifthenelse{\equal{\@upc@degree}{MAMME}}{
    \renewcommand{\degreecode}{MAMME}
    \renewcommand{\degreename}{Master in Advanced Mathematics and Mathematical Engineering}
}{\ifthenelse{\equal{\degreecode}{}}{
    \PackageError{upc-report}{Degree}{Falta el parámetro 'degree'}
}{}}}}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Autores, directores y demás
%
\renewcommand{\and}{, \space}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variables
%
\makeatletter
\newcommand{\bibauthor}[1]{\gdef\@bibauthor{#1}}%
\newcommand{\@bibauthor}{\@latex@warning@no@line{No \noexpand\bibauthor given}}
\newcommand{\director}[1]{\gdef\@director{#1}}%
\newcommand{\@director}{\@latex@warning@no@line{No \noexpand\director given}}
\newcommand{\department}[1]{\gdef\@department{#1}}%
\newcommand{\@department}{\@latex@warning@no@line{No \noexpand\department given}}
\newcommand{\datedefense}[1]{\gdef\@datedefense{#1}}%
\newcommand{\@datedefense}{\@latex@warning@no@line{No \noexpand\datedefense given}}
\newcommand{\company}[1]{\gdef\@company{#1}}%
\newcommand{\@company}{\@latex@warning@no@line{No \noexpand\company given}}
\newcommand{\bibdirector}[1]{\gdef\@bibdirector{#1}}%
\newcommand{\@bibdirector}{\@latex@warning@no@line{No \noexpand\bibdirector given}}

\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Idioma
%
\RequirePackage[spanish,es-tabla,es-ucroman,catalan]{babel}
% \RequirePackage[spanish,es-tabla,es-ucroman]{babel}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Geometría general de las páginas
%
\RequirePackage[
    top=2.5cm,
    bottom=2.5cm,
    left=2cm,
    right=2cm,
]{geometry}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Cabeceras y pies de página
%
\RequirePackage{fancyhdr}
\setlength{\headheight}{10pt}
\pagestyle{fancy}

% Estilos globales
\fancyhf{}
\renewcommand{\chaptermark}[1]{\markboth{\thechapter.\ #1}{}}
\fancyhead[L]{\textcolor{schoolcolor}{\nouppercase{\leftmark}}}
\fancyhead[R]{\textcolor{schoolcolor}{\thepage}}
\renewcommand{\headrulewidth}{0.0pt} %Ficar 0.5pt per a que apareixí una barra horitzontal assota

% Estilos en páginas "plain" (e.g. primera de capítulo)
\fancypagestyle{plain}{%
    \fancyhf{}
    \renewcommand{\headrule}{}
    \renewcommand{\footrule}{}
}


\fancyheadoffset{0cm}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Estilos de capítulo, sección, ...
%
\RequirePackage{titlesec}

\titleformat{\chapter}% TODO: Treure barra horitzontal
    {\fontsize{30}{30}}%
    {\sffamily\fontsize{30}{30}\color{schoolcolor}\thechapter.}%
    {0.6em}%
    {\sffamily\fontsize{30}{30}}
\titlespacing*{\chapter}{0pt}{0pt}{25pt}

\titleformat{\section}%
    {}{\color{schoolcolor}\huge\thesection.}{0.6em}{\huge}
\titleformat{\subsection}%
    {}{\color{schoolcolor}\Large\thesubsection.}{0.6em}{\Large}
\titleformat{\subsubsection}%
    {}{\color{schoolcolor}\large\thesubsubsection.}{0.6em}{\large}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Estilos de la tabla de contenidos
%
\RequirePackage{titletoc}
\setcounter{tocdepth}{2}

\usepackage{tocbasic}
\renewcommand*{\listoffigures}{\listoftoc[\listfigurename]{lof}}
\renewcommand*{\listoftables}{\listoftoc[\listtablename]{lot}}
\setuptoc{lof}{leveldown,totoc}
\setuptoc{lot}{leveldown,totoc}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fuentes
%

\RequirePackage{fontspec}  % Para importar fuentes externas
\usepackage{fourier}
\RequirePackage{microtype} % Mejoras tipográficas generales
% TODO Cambiar los tipos de letra según la guía de estilos de la escuela
\usepackage{fontspec}
\setmainfont{Arial}

% Toda esta configuración permite cambiar la fuente de las formulas matematicas

\usepackage[italic,defaultmathsizes,noasterisk]{mathastext}



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fórmulas matemáticas
%
\RequirePackage{amsmath}   % Mejoras presentación matemática
\RequirePackage{mathtools} % Más mejoras de presentación matemática

%\usepackage{unicode-math}  % For setting math fonts
%\setmathfont{HelveticaNeue-Roman.otf}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Configuración de figuras y tablas
%
\RequirePackage{float}      % Mejorar colocación de elementos flotantes
\RequirePackage{tabularx}   % Tablas más configurables
\newcolumntype{C}{%
    >{\centering\arraybackslash}X%
    }                       % Para tener columnas tipo X centradas
\RequirePackage{booktabs}   % Configuraciones para tablas más bonitas
\RequirePackage{caption}    % Mejora de pies de figuras
\RequirePackage{subcaption} % Pies de subfiguras


\DeclareCaptionFormat{caption-upm}{#1#2~\small #3}
\DeclareCaptionLabelFormat{caption-upm}{\textbf{#1 #2}}
\DeclareCaptionLabelSeparator{caption-upm}{.}

\captionsetup{
    format=caption-upm,
    labelformat=caption-upm,
    labelsep=caption-upm,
}

\newcommand{\figurecenter}[3]{%
    \begin{figure}[h]
        \centering
        \includegraphics[width=0.25\textwidth]{figures/#1}
        \caption{#2}
        \label{fig:#3}  
    \end{figure}
}

\newcommand{\figuretop}[3]{%
    \begin{figure}[t]
        \centering
        \includegraphics[width=0.25\textwidth]{figures/#1}
        \caption{#2}
        \label{fig:#3}  
    \end{figure}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Configuración general de espaciados, geometrías y otros
%
\setlength{\parskip}{1em}
\setlength{\parindent}{0pt}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Configuración para PDF e hipervínculos
%
\RequirePackage[naturalnames]{hyperref}
\makeatletter
\hypersetup{
    pdfauthor={\@author},
    pdftitle={\@title},
    %pdfsubject={\titlecontent},
    %pdfkeywords={\keywords},  % TODO: QUE LAS KEYWORDS SE USEN TAMBIÉN AQUÍ
    pdfcreator={\@author},
    pdfproducer={},
    breaklinks=true,
    linktoc=all,
    plainpages=false,
    unicode=true,
    colorlinks=true,
    anchorcolor={linkcolor},
    citecolor={linkcolor},
    linkcolor={linkcolor},
    urlcolor={linkcolor},
}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Estilos de los listados de código fuente
%
\RequirePackage{listings}
\renewcommand{\lstlistingname}{Llistat}
\renewcommand*{\lstlistlistingname}{Índex de llistat}

\makeatletter
\renewcommand\lstlistoflistings{\bgroup
  \let\contentsname\lstlistlistingname
  \def\l@lstlisting##1##2{\@dottedtocline{1}{1.5em}{2.3em}{##1}{##2}}
  \let\lst@temp\@starttoc \def\@starttoc##1{\lst@temp{lol}}%
  \tableofcontents \egroup}
\makeatother

\definecolor{sbase03}{HTML}{002B36}
\definecolor{sbase02}{HTML}{073642}
\definecolor{sbase01}{HTML}{586E75}
\definecolor{sbase00}{HTML}{657B83}
\definecolor{sbase0}{HTML}{839496}
\definecolor{sbase1}{HTML}{93A1A1}
\definecolor{sbase2}{HTML}{EEE8D5}
\definecolor{sbase3}{HTML}{FDF6E3}
\definecolor{syellow}{HTML}{B58900}
\definecolor{sorange}{HTML}{CB4B16}
\definecolor{sred}{HTML}{DC322F}
\definecolor{smagenta}{HTML}{D33682}
\definecolor{sviolet}{HTML}{6C71C4}
\definecolor{sblue}{HTML}{268BD2}
\definecolor{scyan}{HTML}{2AA198}
\definecolor{sgreen}{HTML}{859900}
\lstset{
    sensitive=true,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    frame=lines,
    xleftmargin=\parindent,
    belowcaptionskip=1\baselineskip,
    basicstyle=\color{sbase00}\ttfamily,
    keywordstyle=\color{scyan},
    commentstyle=\color{sbase1},
    stringstyle=\color{sblue},
    numberstyle=\color{sviolet},
    identifierstyle=\color{sbase00},
    breaklines=true,
    showstringspaces=false,
    tabsize=2
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Listados condicionales
%
\RequirePackage[
    figure,table,lstlisting,equation
    ]{totalcount}  % Contar las veces que aparecen entradas en listados

\addto\captionscatalan{%
    \renewcommand\contentsname{Sumari}
    \renewcommand\listfigurename{Índex de figures}
    \renewcommand\listtablename{Índex de taules}
}


\newcommand\conditionalLoF{\iftotalfigures\listoffigures\fi}
\newcommand\conditionalLoT{\iftotaltables\listoftables\fi}
\newcommand\conditionalLoL{\iftotallstlistings\lstlistoflistings\fi}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Licencia de la memoria
% TODO: Adaptar text en idiomes dinamics.
\RequirePackage[%
    type={CC},%
    modifier={by-nc-sa},%
    version={4.0}%
]{doclicense}

\makeatletter
% Impresión de licencia modificada para que incluya más cosas. Es un
% clon de \docLicenseThis
\newcommand{\licencia}{%
    \setlength{\doclicense@hsize}{\linewidth-\doclicense@imagewidth-\doclicense@imagedistance}%
    \begin{center}
        \begin{minipage}{\doclicense@hsize}
            \ifthenelse{\isempty{\doclicense@hyphenation}}{}{%
                \@nameuse{\doclicense@hyphenation} 
            }%
            \doclicenseLongText Obra derivada de \href{\templaterepository}{\templaterepository}.%
        \end{minipage}
        \hfill
        \begin{minipage}{\doclicense@imagewidth}\doclicenseImage\end{minipage}
    \end{center}
    \vspace{-1.5em}
    Tot canvi respecte a l'obra original és responsabilitat exclusiva del present autor.\\
}
\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Referencias y bibliografía
%
\RequirePackage[backend=biber,style=apa]{biblatex}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Portada
%

\let\titleoriginal\title % Redefinir \title per a que es pugui accedir al contingut.
\renewcommand{\title}[1]{ 
    \titleoriginal{#1} 
    \newcommand{\titlecontent}{#1} 
}

\makeatletter         
\renewcommand\maketitle{{
    \thispagestyle{empty}
    % Barra lateral izquierda y logo fondo
    \AddToShipoutPicture*{%
        \AtPageCenter{%
            \makebox(0.5\paperwidth,0)[r]{%
                \includegraphics[width=0.9\paperwidth]{upc-report/logos/upc/fme_blue.png}
            }%
        }
        \put(0,0){%
            \colorbox{schoolcolor}{%
                \parbox[b][\paperheight]{2cm}{\vfill\hfill}
            }%
        }
    }
    \begin{adjustwidth}{0.5cm}{}
        {\normalsize \MakeUppercase{\universityname} - \universitysurname}\\
        {\normalsize \MakeUppercase{\textbf{\schoolname}}}\\*[1.5em]
        {\normalsize \MakeUppercase{\textbf{\degreename}}}\\
        {\normalsize \MakeUppercase{\reporttype}}\\*[0.5em]
        \begin{hyphenrules}{nohyphenation}
        \raggedright
        \begin{sloppypar}\fontsize{34}{34}\selectfont\bfseries\@title\end{sloppypar}
        \end{hyphenrules}
        \vspace{11cm}
        \parbox[b]{\linewidth}{
            \normalsize
            \textbf{Autor}: \@author \\*[0.5em]
            \textbf{Director}: \@director \\*[0.5em]
            \ifthenelse{\equal{\@upc@external}{false}}
            {\textbf{Departament}: \@department \\*[0.5em]}
            {\textbf{Empresa}: \@company \\*[0.5em]}
            Barcelona, \@datedefense
        }
        \vspace{1.5cm}
        \begin{center}
            \ifthenelse{\equal{\@upc@degree}{GE} \OR \equal{\@upc@degree}{MESIO}}{
            \includegraphics[width=0.35\textwidth]{upc-report/logos/UB_logo.png}
            \hspace{5mm}
            \includegraphics[width=0.55\textwidth]{upc-report/logos/FME_logo.jpg}
            }{
            \hspace{0.4\textwidth}
            \includegraphics[width=0.55\textwidth]{upc-report/logos/FME_logo.jpg}
            }
        \end{center}
    \end{adjustwidth}
    \normalfont
    \normalsize
}}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Licencia
% TODO: Adaptar text en idiomes dinamics.
\makeatletter
\newcommand\makelicense{{
    \footnotesize
    \clearpage
    \thispagestyle{empty}
    ~\vfill
    \par{
        \textit{\@title}\\
        \textbf{Desenvolupat per}: \@author\\
        \textbf{Dirigit per}: \@director\\
        \reporttype, \@datedefense\\
    }
    
    \par{
        \textbf{\schoolname}\\
        \schooladdress
    }
    \newline
    \hrule
    \par{
        Si vols citar aquest treball amb \hologo{BibTeX}, la referència és la següent:

        \texttt{%
            @mastersthesis\{citekey,\\
                title   = \{\@title\},\\
                author  = \{\@bibauthor~, ~\@bibdirector\},\\
                school  = \{\schoolname\},\\
                year    = \{\the\year\},\\
                month   = \{\the\month\},\\
                type    = \{\reporttype\}\\
            \}
        }
    }
    \newline
    \hrule
    \vspace*{-0.5cm}\par{\licencia}
 }}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Agradecimientos
% TODO: Fer que el titol canvii depenent del idioma
\makeatletter
\newcommand{\acknowledgements}[1]{\gdef\@acknowledgements{#1}}%
\newcommand{\@acknowledgements}{}
\newcommand\makeacknowledgements{{
    \ifthenelse{\equal{\@acknowledgements}{}}{}{
        \clearpage
        \thispagestyle{empty}
        \chapter*{Dedicatòria}
        \@acknowledgements
    }
}}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Prefaci
% TODO: Fer que el titol canvii depenent del idioma
\makeatletter
\newcommand{\preface}[1]{\gdef\@preface{#1}}%
\newcommand{\@preface}{}
\newcommand\makepreface{{
    \ifthenelse{\equal{\@preface}{}}{}{
        \clearpage
        \thispagestyle{empty}
        \chapter*{Prefaci}
        \@preface
    }
}}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Resumen y abstract
\makeatletter
\newcommand{\abstract}[2]{%
    \ifthenelse{\equal{#1}{spanish}}{\gdef\@abstractsp{#2}}{}%
    \ifthenelse{\equal{#1}{catalan}}{\gdef\@abstractca{#2}}{}%
    \ifthenelse{\equal{#1}{english}}{\gdef\@abstracten{#2}}{}%
}%
\newcommand{\keywords}[2]{%
    \ifthenelse{\equal{#1}{spanish}}{\gdef\@keywordssp{#2}}{}%
    \ifthenelse{\equal{#1}{catalan}}{\gdef\@keywordsca{#2}}{}%
    \ifthenelse{\equal{#1}{english}}{\gdef\@keywordsen{#2}}{}%
}%

\newcommand\makeresumen{{
    \clearpage
    \thispagestyle{empty}
    \chapter*{Resumen}
    \@abstractsp

    \textbf{Palabras clave}: \@keywordssp
}}

\newcommand\makeabstract{{
    \clearpage
    \thispagestyle{empty}
    \chapter*{Abstract}
    \@abstracten

    \textbf{Keywords}: \@keywordsen
}}

\newcommand\makeresum{{
    \clearpage
    \thispagestyle{empty}
    \chapter*{Resum}
    \@abstractca

    \textbf{Keywords}: \@keywordsca
}}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Glosario
%
\RequirePackage[acronym,section,nowarn]{glossaries}
% Hacemos que no haya salto de página entre glosario y siglas
\renewcommand*{\glsclearpage}{}
\makeglossaries

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Cubierta trasera
%
\makeatletter         
\newcommand{\makebackcover}{
    \clearpage
    \thispagestyle{empty}
    \pagecolor{schoolcolor}
    \AddToShipoutPicture*{%
        \put(0,0){%
            \colorbox{black}{%
                \parbox[b][12cm]{\paperwidth}{\vfill\hfill}
            }%
        }
    }
    \vspace*{\fill}
    \begin{center}
        \includegraphics[width=6cm]{\schoollogo}
    \end{center}
}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Elementos del comienzo del documento
% TODO: Adaptar text en idiomes dinamics: Fer que només surti o resum català o resum castellà
\makeatletter
\AtBeginDocument{%
    \maketitle
    \makelicense
    \makeacknowledgements
    \makepreface
    \makeresum
    %\makeresumen
    \makeabstract
    
    \frontmatter

    \begingroup
        \tableofcontents
    \endgroup

    \mainmatter
}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Elementos del fin del documento
% TODO: Te sistema d'idiomes automatic pero... falta català!

\makeatletter
\AtEndDocument{

    \conditionalLoF
    \conditionalLoT
    \conditionalLoL
    \chapter*{Índex de terminologia}
    \addcontentsline{toc}{section}{Índex de terminologia}

    \printglossaries

    \renewcommand\bibname{Referencies}
    \printbibliography
    
    \makebackcover
}
\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Añadimos el fichero con las entradas de las referencias bibliográficas
%
\addbibresource{references.bib}

\endinput