import config
import numpy as np
import dieumegard

class TableDieumegard:
    def build(self):
        if config.pgsz == "A4":
            paper = "a5paper"
            tm = "21mm"
            bm = "18mm"
            lm = "5mm"
            rm = "5mm"

        alm = r'''\documentclass[10pt, {}]{{report}}'''.format(paper)

        alm = alm + r'''
    %\usepackage[utf8]{inputenc}
    \usepackage[english]{babel}
    \usepackage{fontenc}
    \usepackage{tabularx}
    \usepackage{slashbox}
    '''

        if config.tbls == "m":
            alm = alm + r'''
    \usepackage[table]{xcolor}
    \definecolor{LightCyan}{rgb}{0.88,1,1}
    \usepackage{booktabs}'''

    # to troubleshoot add "showframe, verbose," below:
        alm = alm + r'''
    \usepackage[nomarginpar, top={}, bottom={}, left={}, right={}]{{geometry}}'''.format(tm,bm,lm,rm)

    # Note: \DeclareUnicodeCharacter is not compatible with some versions of pdflatex
        alm = alm + r'''
    \newcommand{\HRule}{\rule{\linewidth}{0.5mm}}
    \setlength{\footskip}{15pt}
    \usepackage[pdftex]{graphicx}
    %\showboxbreadth=50  % use for logging
    %\showboxdepth=50    % use for logging
    %\DeclareUnicodeCharacter{00B0}{\ensuremath{{}^\circ}}
    \begin{document}
    % for the title page and page 2 only...
    \newgeometry{nomarginpar, top=5mm, bottom=13mm, left=20mm, right=14mm}
    \begin{titlepage}'''

        alm = alm + r'''
    \vspace*{2cm}
    \begin{center}
    \textsc{\Large Generated by PyAlmanac}\\[1.5cm]
    %%\includegraphics[width=0.4\textwidth]{./Ra}\\[1cm]
    \textsc{\huge The Nautical Almanac for the Sun}\\[0.7cm]'''


        if config.tbls == "m":
            alm = alm + r'''
    \begin{center} \large
    \emph{Author:}\\
    Andrew \textsc{Bauer}\\[6Pt]
    \emph{Original concept from:}\\
    Enno \textsc{Rodegerdts}
    \end{center}'''
        else:
            alm = alm + r'''
    \begin{center} \large
    \emph{Original author:}\\
    Enno \textsc{Rodegerdts}\\[6Pt]
    \emph{Enhancements:}\\
    Andrew \textsc{Bauer}    
    \end{center}'''

        alm = alm + r'''
    \vfill
    {\large \today}
    \HRule \\[0.6cm]
    \end{center}
    \begin{description}\footnotesize
    \item[Disclaimer:] These are computer generated tables. Use on your own risk. 
    The accuracy has been checked as good as possible but can not be guaranteed. 
    This means, if you get lost on the oceans because of errors in this publication I can not be held liable. 
    For security relevant applications you should buy an official version of the nautical almanac.
    \end{description}
\end{titlepage}
'''

        alm = alm + r'''
    \setcounter{page}{2}    % otherwise it's 1
    \vspace*{2cm}
    \noindent
    DIP corrects for height of eye over the surface. This value has to be subtracted from the sextant altitude ($H_s$). The  correction in degrees for height of eye in meters is given by the following formula: 
    \[d=0.0293\sqrt{m}\]
    This is the first correction (apart from index error) that has to be applied to the measured altitude.\\[12pt]
    \noindent
    The next correction is for refraction in the earth's atmosphere. As usual this table is correct for 10$^\circ$C and a pressure of 1010 hPa. This correction has to be applied to apparent altitude ($H_a$). The exact values can be calculated by the following formula.
    \[R_0=\cot \left( H_a + \frac{7.31}{H_a+4.4}\right)\]
    For other than standard conditions, calculate a correction factor for $R_0$ by: \[f=\frac{0.28P}{T+273}\] where $P$ is the pressure in hectopascal and $T$ is the temperature in $^\circ$C.\\[12pt]
    \noindent
    Semidiameter has to be added for lower limb sights and subtracted for upper limb sights. The value for semidiameter is tabulated in the daily pages.\\[12pt]
    \noindent
    To correct your sextant altitude $H_s$ do the following:
    Calculate $H_a$ by
     \[H_a= H_s+I-d\] 
    where $I$ is the sextant's index error and $d$ is DIP. Then calculate the observed altitude $H_o$ by
    \[H_o= H_a-R+P\pm SD\]
    where $R$ is refraction, $P$ is parallax and $SD$ is the semidiameter.\\[12pt]
    \noindent
    Sight reduction tables can be downloaded for the US government's internet pages. Search for HO-229 or HO-249.  These values can also be calculated with two, relatively simple, formulas:
    \[ \sin H_c= \sin L \sin d + \cos L \cos d \cos LHA\]
    and
    \[\cos A = \frac{\sin d - \sin L \sin H_c}{\cos L \cos H_c}\]
    where $A$ is the azimuth angle, $L$ is the latitude, $d$ is the declination and $LHA$ is the local hour angle. The azimuth ($Z_n$) is given by the following rule:
    \begin{itemize}
    \item if the $LHA$ is greater than $180^\circ$,\quad$Z_n=A$
    \item if the $LHA$ is less than $180^\circ$,\quad$Z_n = 360^\circ - A$
    \end{itemize}
\restoregeometry    % so it does not affect the rest of the pages'''

        angles = np.arange(270, 285, 1)
        angles_str = [r'''\textbf{{{}}}'''.format(str(angle)) for angle in angles]
        formats = '||r' + 'X'*len(angles_str) + 'l||'
        formats = '{'+formats + '}'
        first_row = r'\backslashbox{min}{deg}& ' + r'&'.join(angles_str) + r"&\\"

        angles_comp = 359-angles
        angles_comp_str = [r'''\textbf{{{}}}'''.format(str(angle)) for angle in angles_comp]
        last_row = r'&' + r'&'.join(angles_comp_str) + r"& \\"

        minutes = np.arange(0,61,1)

#    \begin{{tabular*}}{{0.2\textwidth}}[t]{{@{{\extracolsep{{\fill}}}}{}}}

        alm = alm + r'''
    \noindent
    \tiny
    \begin{{tabularx}}{{\textwidth}}{}
    '''.format(formats)

        alm += r'''\hline'''
        alm += r'''\\'''
        alm += first_row

        for num, minute in enumerate(minutes):
            values = ["{:.4f}".format(abs(dieumegard.table_1(angle, minute))) for angle in angles]
            
            if num%5==0:
                alm+=r'\\'

            row = r'''\textbf{{{}}}&'''.format(minute) + r'&'.join(values) + r'''&\textbf{{{}}} \\'''.format(60-minute)
            alm += row
        
        alm += last_row
        alm = alm + r'''
    \\
    \hline
    \end{tabularx}
        '''

        alm = alm + '''
    \end{document}'''
        return alm