%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% liathesis class
%
% Mayeul Mathias 2018
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\NeedsTeXFormat{LaTeX2e}


% class options
\RequirePackage{xkeyval}                        % options parsing
\RequirePackage{xstring}                        % string comparison

% option to select the main language of the document (allows french and english)
\global\def\@DocumentLang{}%
\DeclareOptionX{lang}{%
 \IfEqCase{#1}{%
  {french}{%
    \global\def\@DocumentLang{french}%
   }%
   {english}{%
    \global\def\@DocumentLang{english}%
   }%
 }[\ClassError{liathesis}{Invalid language (french and english supported): '#1'}]%
}

\global\def\@DocumentMode{}%
\DeclareOptionX{mode}{%
 \IfEqCase{#1}{%
  {draft}{%
    \global\def\@DocumentMode{draft}%
   }%
   {final}{%
    \global\def\@DocumentMode{final}%
   }%
 }[\ClassError{liathesis}{Invalid mode (draft and final supported): '#1'}]
}

\global\def\@DocumentFontSize{}%
\DeclareOptionX{size}{%
 \global\def\@DocumentFontSize{#1}%
}

\DeclareOptionX*{\ClassWarning{`\CurrentOption' ignored}} % warning on unknown options


\ExecuteOptionsX{                               % default options
 lang=french,size=12pt,mode=final%
}
\ProcessOptionsX{}\relax{}                      % parses options

% base class and encoding
\ProvidesClass{core/liathesis}[2019/10/01]
\LoadClass[
 a4paper, twoside,%
 \@DocumentFontSize%,
 %\@DocumentMode%
]{book}                                         % base class
\let\@DocumentFontSize\undefined

\RequirePackage[utf8]{inputenc}				    % use source file containing diacritics
\RequirePackage[T1]{fontenc}				    % select font encoding and allow hyphenation
\RequirePackage[%
 french, english,
 main=\@DocumentLang
]{babel}                                       % multi languages support
\RequirePackage{xspace}                        % recommanded with frenchb (spaces after \ier etc.)

% geometry and general page layout
\def\@GeometryShowFrame{false}
\IfStrEq{\@DocumentMode}{draft}{%
 \def\@GeometryShowFrame{true}%
 \RequirePackage{layout}
}{}
\RequirePackage[showframe=\@GeometryShowFrame]{geometry}
\let\@GeometryShowFrame\undefined

\RequirePackage{fancyhdr}                       % formatting of headers and footers
\RequirePackage{setspace}                       % control space between lines
\RequirePackage[autostyle=true]{csquotes}       % improves quotes rendering

\geometry{%                                     % default geometry
 a4paper, twoside,
 headheight=15mm,
 width=140mm,
 top=25mm,
 bottom=25mm,
 bindingoffset=6mm
}
\pagestyle{plain}                               % default page style

\RequirePackage[                                % Generates links in PDF file (recommended to be last loaded package)
 hypertexnames=true                              % Allows to reset counters without messing with hyperlinks
]{hyperref}
\RequirePackage{bookmark}                       % Improves performances for hyperref

% TODO: Replace with titletoc or etoc
\RequirePackage{minitoc}                        % allows to display a toc at each chapter
\mtcsetdepth{minitoc}{2}                        % displays up to subsections
\setlength{\mtcindent}{10pt}                    % allows longer titles

\renewcommand{\cleardoublepage}{%               % from fancyhdr (set clear pages empty)
 \clearpage%
 \if@twoside%
  \ifodd\c@page%
  \else%
   \hbox{}%
   \thispagestyle{empty}%
   \newpage%
   \if@twocolumn%
    \hbox{}%
    \newpage%
   \fi%
  \fi%
 \fi%
}

% Sectionning
%\RequirePackage{sectsty}

% Add part
\newcommand{\@ThesisPartNoStar}[1]{%
 \part{#1}%
}

\newcommand{\@ThesisPartStar}[1]{%
 \part*{%
  #1%
  %\phantomsection{}%
 }%
 \addcontentsline{toc}{part}{#1}%
}

% Add chapter (with or without toc)
\define@boolkey{CHAPTER}{toc}[true]{}
\newcommand{\@ThesisChapterNoStar}[2][toc=true]{%
 \setkeys{CHAPTER}{#1}%
 \chapter{#2}%
 \ifKV@CHAPTER@toc%
  \minitoc%
 \fi%
}

\newcommand{\@ThesisChapterStar}[1]{
 \chapter*{#1}
 \addcontentsline{toc}{chapter}{#1}
 \adjustmtc
}

\newcommand{\@ThesisSectionNoStar}[1]{\section{#1}}
\newcommand{\@ThesisSectionStar}[1]{
 \section*{#1}
 \addcontentsline{toc}{section}{#1}
 %\adjuststc
}

\newcommand{\@ThesisSubsectionNoStar}[1]{\subsection{#1}}
\newcommand{\@ThesisSubsectionStar}[1]{
 \subsection*{#1}
 \addcontentsline{toc}{subsection}{#1}
}

\newcommand{\AddPart}{\@ifstar\@ThesisPartStar\@ThesisPartNoStar}
\newcommand{\AddChapter}{\@ifstar\@ThesisChapterStar\@ThesisChapterNoStar}
\newcommand{\AddSection}{\@ifstar\@ThesisSectionStar\@ThesisSectionNoStar}
\newcommand{\AddSubsection}{\@ifstar\@ThesisSubsectionStar\@ThesisSubsectionNoStar}
\newcommand{\AddParagraph}[1]{\paragraph{#1} \hspace{0pt} \\}
%\newcommand{\AddParagraph}[1]{\paragraph{#1} \mbox{}}

% Appendices
\RequirePackage[toc,page,title]{appendix}

\renewcommand{\addappheadtotoc}{%
 \phantomsection{}%
 \addcontentsline{toc}{part}{\appendixtocname}%
}

%\newenvironment{Appendices}{%
%\appendix
%\part*{%
%\appendixpagename%
%\phantomsection{}%
%\addcontentsline{toc}{part}{\appendixpagename}%
%}
%\setcounter{chapter}{0}
%\def\thechapter{\Alph{chapter}}
%\renewcommand{\chaptername}{\appendixname}
%}{}

\newcommand{\BlankPage}{%                       % insert blank double page
 \begingroup
 \pagestyle{empty}
 \cleardoublepage
 \null
 \cleardoublepage
 \endgroup
}

% frontcover, backcover and page design
\RequirePackage{tikz}						    % for vector graphics
\usetikzlibrary{positioning} 				    % relative positioning
\usetikzlibrary{calc}                           % extends coordinate calculation
\RequirePackage[useregional]{datetime2}         % date display
%\RequirePackage{mathpazo}                       % Palatino font family (roman)
\RequirePackage{tabularx}                       % tabular spacing
%\RequirePackage{merriweather}

\global\def\@TheSubtitle{}
\newcommand{\subtitle}[1]{%
 \makeatletter%
 \global\def\@TheSubtitle{#1}%
 \makeatother%
}

\renewcommand{\date}[3]{%
 \makeatletter%
 \global\def\@date{\DTMdisplaydate{#1}{#2}{#3}{-1}}%
 \makeatother%
}

\newcommand{\@PrintTitle}{%
 \huge{\@title}%
 \par%
 \ifx\@TheSubtitle\empty%
 \else%
  \vspace{0.5cm}
  \textit{\Large{\@TheSubtitle}}
  \par%
 \fi%
}

% Jury compostion formatting
\define@choicekey*{JURY}{gender}{male,female}{%
 \newcommand{\@TheGender}{\csname gender#1name\endcsname}%
}
\newcommand{\Member}[5][]{%
 %\presetkeys{JURY}{gender=male}{}%
 \setkeys{JURY}{#1}%
 \@TheGender & #2 & #3, #4 & #5\\%
}
\global\def\@TheJury{}
\newcommand{\Jury}[1]{%
 \global\def\@TheJury{%
  \begin{tabularx}{\textwidth}{@{} l l X l @{}}%
   #1%
  \end{tabularx}%
 }%
}

% Abstracts
\global\def\@TheAbstractFr{}
\global\def\@TheAbstractEn{}
\newcommand{\Abstract}[2][\@DocumentLang]{%
 \IfEqCase{#1}{%
  {french}{%
    \global\def\@TheAbstractFr{#2}
   }%
   {english}{%
    \global\def\@TheAbstractEn{#2}
   }%
 }[\ClassError{liathesis}{Invalid language (french and english supported): '#1'}]
}

% Keywords
\global\def\@TheKeywordsFr{}
\global\def\@TheKeywordsEn{}
\newcommand{\Keywords}[2][\@DocumentLang]{%
 \IfEqCase{#1}{%
  {french}{%
    \global\def\@TheKeywordsFr{#2}
   }%
   {english}{%
    \global\def\@TheKeywordsEn{#2}
   }%
 }[\ClassError{liathesis}{Invalid language (french and english supported): '#1'}]
}

\global\def\@TheEndOfDocumentContents{}
\newenvironment{Thesis}[2]{
 \global\def\@TheEndOfDocumentContents{#2}
 \BeginOfDocument{#1}
}{
 \EndOfDocument{\@TheEndOfDocumentContents}
}

% Cover pages design
\newenvironment{@Cover}{%
 % \let\orignewcommand\newcommand%
 % \let\newcommand\renewcommand%
 % \makeatletter%
 % \input{bk10.clo}%
 % \merriweather
 % \makeatother
 % \let\newcommand\orignewcommand
 %\merriweather
 %\renewcommand{\huge}{\Large}%
 %\renewcommand{\large}{\normalsize}%
 %\renewcommand{\normalsize}{\scriptsize}%
 %\fontfamily{ppl}\selectfont
 \newgeometry{%
  noheadfoot,nomarginpar,%
  vmargin=0.5in,%
  hmargin=0.75in%
 }%
 \pagestyle{empty}%
 \begin{spacing}{1.25}%
  }{%
 \end{spacing}%
 \restoregeometry%
}

\newcommand{\@SetMainLayout}{				    % set the document layout with respect to the twoside option
 \fancyhead{}                                % clear all header fields
 \fancyhead[LE]{\nouppercase{\leftmark}}     % right on event pages
 \fancyhead[RO]{\nouppercase{\rightmark}}    % left on odd pages
 \fancyfoot{}                                % clear all footer fields
 \fancyfoot[CE,CO]{\thepage}
 \renewcommand{\headrulewidth}{0.4pt}
 \renewcommand{\footrulewidth}{0pt}
 
 \pagestyle{fancy}
 
 \IfStrEq{\@DocumentMode}{draft}{
  \layout
 }{}
}

% glossaries, appendices, bibliographic and references settings
\RequirePackage{glossaries-extra}               % Loads glossaries
\makeglossaries
\setabbreviationstyle{long-short}
\setabbreviationstyle[acronym]{long-short}

\def\@BibLatexStyle{alphabetic}%
% \def\@BibLatexStyle{authoryear}%
%\def\@BibLatexStyle{authoryear}%
%\IfStrEq{\@DocumentMode}{draft}{%
%    \def\@BibLatexStyle{draft}%
%}{}

\RequirePackage[
 backend=biber,
 maxcitenames=1,
 maxbibnames=99,
 bibstyle=\@BibLatexStyle,
 citestyle=authoryear
]{biblatex}		                    		    % uses biblatex and biber (instead of bibtex)
\let\@BibLatexStyle\undefined

%\RequirePackage[numbers]{natbib}		        % incompatible with biblatex
%\RequirePackage[numbers]{multibib}		        % incompatible with biblatex
\RequirePackage{doi}					        % displays DOIs in the bibliography
%\AtEveryCite{\restorecommand\mkbibnamefamily}	% avoid small caps in citations (French)
%\setlength\bibitemsep{0.9\itemsep}		% reduce space between bibliographic items

% Front cover


\input{firstpage.tex}


\newcommand{\@TitleFooter}{%
 \begin{tikzpicture}[every node/.style={inner sep=0,outer sep=0}]
  \node[anchor=north west] (logo_lia) at (0.1mm,0) {%
  	\fpbl
  } ;
  \node[anchor=north east, align=right] (text_lia) at (\textwidth - 0.1mm, 0) {
  	\fpbr
  	%
   %\normalsize{\textsl{\MakeUppercase{}}}% Anciennement "Laboratoire Informatique d'Avignon
   
  } ;
  \coordinate[draw=none, above=0.2cm of logo_lia.north west] (line_start) ;
  \coordinate[draw=none, above=0.2cm of text_lia.north east] (line_end) ;
  \draw (line_start) -- (line_end);
 \end{tikzpicture}%
}

\newcommand{\@FrontCover}{%
 \cleardoublepage%
 \begin{@Cover}
  \centering
  % header
  \@TitleHeader%
  \par
  \vspace{0.5cm}%
  \textbf{\huge{\MakeUppercase{\thesisname}}}%
  \par%
  \vspace{1cm}%
  \large{\thesisdefenselocation}%
  \par%
  \vspace{0.5cm}%
  \textbf{\normalsize{\MakeUppercase{\thesisspecialtyname}}}%
  \par%
  \vspace{0.5cm}%
  \large{%
   École Doctorale 536 \enquote{Agrosciences \& Sciences}\\%
   Laboratoire Informatique d'Avignon (EA 4128)%
  }%
  \par%
  \vspace{\fill}%
  \vspace{1cm}%
  \@PrintTitle%
  \vspace{1cm}%
  \normalsize{\thesisby}\\%
  \textbf{\large{\@author}}%
  \par%
  \vspace{\fill}%
  \vspace{0.5cm}%
  \begin{scriptsize}%
   \thesisdefensedate{\@date}\\%
   \vspace{0.5cm}%
   \@TheJury%
   \par%
  \end{scriptsize}%
  \vspace{0.5cm}%
  % footer
  \@TitleFooter%
 \end{@Cover}%
 \cleardoublepage%
}

% Back cover
\newcommand{\@BackCover}{%
 \cleardoublepage
 \null
 \thispagestyle{empty}
 \clearpage
 \begin{@Cover}
  \begin{center}%
   \includegraphics[height=1.5cm]{images/avignon_universite_horizontal.jpg}%
   \par%
   \vspace{2cm}%
   \@PrintTitle%
   \vspace{1cm}%
   \normalsize{\thesisby}\\%
   \textbf{\large{\@author}}%
   \par%
  \end{center}%
  \vspace{2cm}%
  \ifx\@TheAbstractFr\empty%
   \ClassWarning{liathesis}{Missing abstract in french}
  \else%
   \noindent
   \begin{otherlanguage}{french}
    \textbf{Résumé~:} \@TheAbstractFr%
   \end{otherlanguage}
   \par
  \fi%
  \medskip%
  \ifx\@TheKeywordsFr\empty%
   \ClassWarning{liathesis}{Missing keywords in french}
  \else%
   \noindent
   \begin{otherlanguage}{french}
    \textbf{Mots-clés~:} \@TheKeywordsFr%
   \end{otherlanguage}%
   \par
  \fi%
  \vspace{1cm}%
  \ifx\@TheAbstractEn\empty%
   \ClassWarning{liathesis}{Missing abstract in english}
  \else%
   \noindent
   \begin{otherlanguage}{english}
    \textbf{Abstract~:} \@TheAbstractEn%
   \end{otherlanguage}
   \par
  \fi%
  \medskip
  \ifx\@TheKeywordsEn\empty%
   \ClassWarning{liathesis}{Missing keywords in english}%
  \else%
   \noindent
   \begin{otherlanguage}{english}%
    \textbf{Keywords~:} \@TheKeywordsEn%
   \end{otherlanguage}%
   \par%
  \fi%
  \vspace{2cm}%
  \vspace{\fill}%
  \begin{center}%
   \includegraphics[height=1.5cm]{images/lia_complet.pdf}%
  \end{center}%
 \end{@Cover}
}

% Bibliography
\newcommand{\personalpublicationsname}{Personal publications}
%\AtDataInput{%                              % Cite all personnal publications
%    \ifkeyword{personal}%
%    {
%        \AtBeginDocument{
%            %\nocite{\thefield{entrykey}}
%        }
%    }%
%    {}%
%}
% Personal publications
\DeclareBibliographyCategory{personal}
\newcommand{\AddPersonalPublication}[1]{%
 \addtocategory{personal}{#1}%
 \nocite{#1}
}

% Begin of document (insert title page and table of contents)
\newcommand{\BeginOfDocument}[1]{%
 \dominitoc                                      % allows to use minitoc
 \dominilof                                      % allows to use minitof
 \dominilot                                      % allows to use minitot
 \pagestyle{plain}%
 \frontmatter%
 \@FrontCover%
 \BlankPage%
 \onehalfspacing%
 \setcounter{page}{1}%
 #1%
 \cleardoublepage%
 \begin{singlespace}%
  \pdfbookmark[chapter]{\contentsname}{toc}%
  \tableofcontents%
 \end{singlespace}%
 \cleardoublepage%
 \mainmatter%
 \@SetMainLayout%
}

% End of document (figures, tables and bibliography)
\newcommand{\EndOfDocument}[1]{
 #1%
 \backmatter%
 \begin{singlespace}%
  
  \cleardoublepage%
  \bookmarksetup{startatroot}%
  \printglossaries%
  
  \cleardoublepage%
  \listoffigures%
  \addcontentsline{toc}{chapter}{\listfigurename}%
  
  \cleardoublepage%
  \listoftables%
  \addcontentsline{toc}{chapter}{\listtablename}%
  
  \cleardoublepage%
  \printbibheading[heading=bibintoc]%
  \printbibliography[heading=subbibintoc, notcategory=personal]%
  \begin{refcontext}[sorting=ynt]%
   \printbibliography[heading=subbibintoc, title=\personalpublicationsname, category=personal]%
  \end{refcontext}%
  \BlankPage%
  \@BackCover%
 \end{singlespace}%
}

% miscellaneous
\RequirePackage{icomma}                         % treats the comma as a digit separator when required

% Translations
\addto\captionsfrench{\renewcommand{\contentsname}{Sommaire}}
\addto\captionsfrench{\renewcommand{\figurename}{Figure}}
\addto\captionsfrench{\renewcommand{\listfigurename}{Liste des figures}}
\addto\captionsfrench{\renewcommand{\listtablename}{Liste des tableaux}}

% Translations for minitoc (uses babel commands instead of mtcselectlanguage)
%\mtcselectlanguage{french}                     % prefer use the babel commands
\renewcommand{\ptctitle}{\contentsname}
\renewcommand{\plftitle}{\listfigurename}
\renewcommand{\plttitle}{\listtablename}
\renewcommand{\mtctitle}{\contentsname}
\renewcommand{\mlftitle}{\figurename}
\renewcommand{\mlttitle}{\tablename}
\renewcommand{\stctitle}{\contentsname}
\renewcommand{\slftitle}{\listoffigures}
\renewcommand{\slttitle}{\listoftables}

% Translations for appendices
\addto\captionsfrench{\renewcommand{\appendixname}{Annexe}}
\addto\captionsfrench{\renewcommand{\appendixtocname}{Annexes}}
\addto\captionsfrench{\renewcommand{\appendixpagename}{\color{cerulean}\Huge\bfseries\sffamily Annexes}}

% Translations for bibliography
\DefineBibliographyStrings{french}{%
 bibliography = {Bibliographie},
 references   = {Ouvrages de référence}
}
\addto\captionsfrench{\renewcommand{\personalpublicationsname}{Publications personnelles}}
