%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2012 Robert Krause
% Copyright ((copyrightdate)) Louis Paternault
% License : Creative Commons Attribution License
%
% Produced by ((version)).
% http://git.framasoft.org/spalax/scal
%
% Compile it using `lualatex`
%
% History:
% The calendar has been posted by original author Robert Krause on TeXample.net [1] on 13 July 2012.
% I (Louis Paternault) used it as a base for this template, and added the weekly planner.
%
% [1] http://www.texample.net/tikz/examples/a-calender-for-doublesided-din-a4/
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Compile it twice using LuaLaTeX
%$ lualatex $basename
%$ lualatex $basename

\documentclass[10pt]{article}

\IfFileExists{hyperref.sty}{
  \usepackage[
      pdftitle={Weekly planner for years (* for year in years *)(( year ))(* endfor *)},
      pdfcreator={LuaLaTeX, using a file generated by (( version ))},
  ]{hyperref}
}{
  % Hyperref not loaded
}

\usepackage{fontspec}
\renewcommand{\familydefault}{\sfdefault}

\usepackage[(( variables.language ))]{babel}
\usepackage[(( variables.language ))]{translator} % Internationalized  Month and Day names

\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{calendar}
\usetikzlibrary{fit}
\usepackage{tikzpagenodes}

\usepackage[
  a6paper,
  margin=5mm,
]{geometry}

% Names of Holidays are inserted by employing this macro. Arguments:
% - #1: First day of holidays
% - #2: Holiday name
\def\printholiday#1#2{
  \node [anchor=west, align=right, text width={\cellwidth-\cellsep-7pt}] at
    ($(cal-#1.west)$) {\tiny{#2\par}};
}

% Display weeks
% - #1 Day in which week is to be written
% - #2 Week number (as LaTeX code)
\def\printweek#1#2{
    \node [anchor=east, align=center, color=gray] at
    ($(cal-#1.east)$) {{\tiny #2\par}};
}

% Display the year. Arguments are:
% - #1: Year
% - #2: First month of year
% - #3: Last month of year
\newcommand{\printyear}[3]{
  \draw[fill=red!70, draw=none]
    ($(cal-#1-#2-01.north west)+(0, {2*\cellheight})$)
    rectangle
    ($(cal-#1-#3-01.south east)+(0, {2*\cellheight})$)
    node[midway, text=white]{\textbf{#1}};
}

% Display day (planner)
\usepackage{xparse}
\usepackage{xstring}
\NewDocumentCommand{\plannerday}{O{big}mmmmm}{
\begin{tikzpicture}[overlay, remember picture]
  \node[
      inner sep=0pt,
      fit={
        ($(current page text area.north west) + (#2 * \textwidth, {-#3*\textheight})$)
        ($(current page text area.north west) + ({(#2+1/3) * \textwidth}, {(-#4-#3)*\textheight})$)
      },
    ] (day) {};
  \draw[ultra thick, opacity=.8, rounded corners] (day.north west) rectangle (day.south east) node[midway]{};
  \node[
      anchor=center,
      minimum height=2em,
    ]
    (name)
    at ($(day.north) + (0, -1em)$)
    {\large\textbf{\pgfcalendarweekdayname{#5} #6}};
  \draw (name.south -| day.east) -- (name.south -| day.west);

  \node[inner sep=0pt, fit=(day.south east) (name.south -| day.west)] (hours) {};
  \foreach \hour in {(( variables.hours.start )), ..., (( variables.hours.end - 1 ))}{
    \node[anchor=north west, inner sep=2pt] (hour) at ($(hours.north west)!{(\hour - (( variables.hours.start )))/(( variables.hours.end - variables.hours.start ))}!(hours.south west)$) {
      \IfStrEq{#1}{big}{
        \hour
      }{
        \small\hour
      }
    };
    \draw[darkgray] (hour.north west) -- (hour.north west -| day.east);

    \IfStrEq{#1}{big}{
      \node[inner sep=0pt] (halfhour) at ($(hours.north west)!{(\hour - (( variables.hours.start )) + .5)/(( variables.hours.end - variables.hours.start ))}!(hours.south west)$) {};
      \draw[dotted] (halfhour.north east) -- (halfhour.north west -| day.east);
    }{}
  }
\end{tikzpicture}
}
\NewDocumentCommand{\plannerweek}{mm}{
\begin{tikzpicture}[overlay, remember picture]
  \node[
      inner sep=0pt,
      fit={
        (current page text area.north east)
        ($(current page text area.north east) - (1/3 * \textwidth, {.2*\textheight})$)
      },
    ] (box) {};
    \node[anchor=north, text width={1/3 * \textwidth}, align=center] (month) at (box.north) {\Large\textbf{#1}};
    \node[anchor=north, text width={1/3 * \textwidth}, align=center] at (month.south) {\textbf{\Large #2}};
\end{tikzpicture}
}

\newcounter{today}
\NewDocumentCommand{\doublepage}{m}{
  \setcounter{today}{#1}

  \pgfcalendarjuliantodate{#1}{\myyear}{\mymonth}{\myday}
  \plannerday{0/3}{0}{1}{0}{\myday}
  \let\mondayyear\myyear
  \let\mondaymonth\mymonth

  \stepcounter{today}\pgfcalendarjuliantodate{\value{today}}{\myyear}{\mymonth}{\myday}
  \plannerday{1/3}{0}{1}{1}{\myday}

  \stepcounter{today}\pgfcalendarjuliantodate{\value{today}}{\myyear}{\mymonth}{\myday}
  \plannerday{2/3}{0}{1}{2}{\myday}

  \newpage

  \stepcounter{today}\pgfcalendarjuliantodate{\value{today}}{\myyear}{\mymonth}{\myday}
  \plannerday{0/3}{0}{1}{3}{\myday}

  \stepcounter{today}\pgfcalendarjuliantodate{\value{today}}{\myyear}{\mymonth}{\myday}
  \plannerday{1/3}{0}{1}{4}{\myday}

  \stepcounter{today}\pgfcalendarjuliantodate{\value{today}}{\myyear}{\mymonth}{\myday}
  \plannerday[small]{2/3}{1/5}{.4}{5}{\myday}

  \stepcounter{today}\pgfcalendarjuliantodate{\value{today}}{\myyear}{\mymonth}{\myday}
  \plannerday[small]{2/3}{3/5}{.4}{6}{\myday}

  \IfStrEq{\mondaymonth}{\mymonth}{
    \plannerweek{\pgfcalendarmonthname{\mymonth}}{\myyear}
  }{
    \IfStrEq{\mondayyear}{\myyear}{
      \plannerweek{\pgfcalendarmonthname{\mondaymonth}\\\pgfcalendarmonthname{\mymonth}}{\myyear}
    }{
      \plannerweek{\pgfcalendarmonthname{\mondaymonth}\\\mondayyear}{\pgfcalendarmonthname{\mymonth}\\\myyear}
    }
  }
  \newpage
}

\usepackage{etoolbox}
\NewDocumentCommand{\blankpages}{m}{
  \ifnumgreater{#1}{0}{
    \foreach \i in {1, ..., #1}{
        ~

        \newpage
      }
    }{}
}

\newcommand{\cellwidth}{\textwidth/(( count.months / 2 ))}
\newcommand{\cellheight}{\textheight/34}
\newcommand{\cellsep}{2pt}

\NewDocumentCommand{\calendar}{}{
  \begin{tikzpicture}[every day/.style={anchor = north}]
    \pgftransformyshift{\cellheight}
    \calendar[
      dates=(( start.year ))-(( start.month ))-01 to (( end.year ))-(( end.month ))-last,
      name=cal,
      day yshift = \cellheight,
      day code=
      {
        \node[name=\pgfcalendarsuggestedname,every day,shape=rectangle,
        minimum height= \cellheight, draw=black, text width = {\cellwidth-\cellsep-7pt}]{};
        \draw ($(\pgfcalendarsuggestedname.west)+(0em,0)$)           node[anchor=west, color=gray]{\footnotesize \tikzdaytext};
        \draw ($(\pgfcalendarsuggestedname.west)+(1.5em,0)$) node[anchor=west, color=gray]{\tiny \pgfcalendarweekdayshortname{\pgfcalendarcurrentweekday}};
      },
      execute before day scope=
      {
        \ifdate{day of month=1}
        {
          % Shift right
          \pgftransformxshift{\cellwidth}
          % Print month name
          \draw (0,0) node [shape=rectangle, minimum height= \cellheight,
              text width = {\cellwidth-\cellsep-7pt}, fill = red!70, text= white, draw = red!70, text centered]
            {\textbf{\tiny\pgfcalendarmonthname{\pgfcalendarcurrentmonth}}};
        }{}
        \ifdate{workday}
        {
          % normal days are white
          \tikzset{every day/.style={fill=white}}
          % Holidays
          (* for holiday in holidays *)
          \ifdate{between=((holiday.start)) and ((holiday.end))}{%
            \tikzset{every day/.style={fill=gray!30}}}{}
          (* endfor *)
        }{}
        % Saturdays
        \ifdate{Saturday}{\tikzset{every day/.style={fill=red!10}}}{}
        % Sundays
        \ifdate{Sunday}{\tikzset{every day/.style={fill=red!20}}}{}
      },
     execute at begin day scope=
      {
        % each day is shifted down according to the day of month
        \pgftransformyshift{-{\cellheight * \number\pgfcalendarcurrentday}}
      }
    ];

      % Print week numbers
      (* for week in weeks if week.work and week.iso *)
        \printweek{((week.date))}{((week.work)) / ((week.iso))}
      (* endfor *)
      (* for week in weeks if week.iso and not week.work *)
        \printweek{((week.date))}{((week.iso))}
      (* endfor *)
      (* for week in weeks if week.work and not week.iso*)
        \printweek{((week.date))}{((week.work))}
      (* endfor *)

      % Print name of Holidays
      (* for holiday in holidays if holiday.name *)
      \printholiday{((holiday.start))}{((holiday.name))}
      (* endfor *)

      % Print years
      (* for year, boundaries in years.items() *)
        \printyear{((year))}{((boundaries[0]))}{((boundaries[1]))}
      (* endfor *)
    \end{tikzpicture}
}

\usepackage{adjustbox}
\newsavebox{\mysavebox}

\pagestyle{empty}

\begin{document}

\blankpages{(( variables.blankpages.beforetitle ))}

\begin{tikzpicture}[overlay, remember picture]
  \draw (current page.center) node{\Huge
      (* set yearslist = years.keys()|sort|list *)
      (* if years|length == 1 *)
        (( yearslist[0] ))
      (* else *)
      (( yearslist[0] )) --- (( yearslist[-1] ))
      (* endif *)
  };
\end{tikzpicture}
\newpage

\blankpages{(( variables.blankpages.aftertitle ))}

% Break a figure across two pages.
% Thanks Martin Scharrer for the hint
% https://tex.stackexchange.com/a/22836
\begin{lrbox}{\mysavebox}
    \calendar
\end{lrbox}

\begin{center}
    \clipbox{0 0 {\textwidth} 0}{\usebox{\mysavebox}}%
\end{center}
\newpage

\begin{center}
    \clipbox{{\textwidth} 0 0 0}{\usebox{\mysavebox}}%
\end{center}
\newpage

\blankpages{(( variables.blankpages.beforeplanner ))}

\newcount\currentdate
\pgfcalendardatetojulian{(( start ))}{\currentdate}

% If the start date is not a monday, go back in time to the previous monday
\newcount\weekday
\pgfcalendarjuliantoweekday{\the\currentdate}{\weekday}
\advance\currentdate -\the\weekday \relax

\foreach \i in {0, ..., (( count.weeks - 1 )) }{
  \pgfmathaddtocount{\currentdate}{7*\i}
  \doublepage{\the\currentdate}
}

\blankpages{(( variables.blankpages.afterplanner ))}

\end{document}
