1#!/usr/bin/env python3
  2
  3"""CHART default theme file."""
  4
  5# long lines
  6# pylint: disable=C0301
  7
  8import logging
  9from datetime import datetime, timedelta
 10
 11from django.template import Template
 12from django.template import Context
 13
 14from chart.common.path import Path
 15from chart.project import settings
 16from chart.common.prettyprint import show_time
 17from chart.common.path import Path
 18
 19# List of files in this directory which should be copied over
 20embed = [
 21    "theme.css",
 22    "theme_print.css",
 23]
 24
 25# suffix used to create filenames for thumbnail images
 26thumbnail_suffix = 'S'
 27
 28# If the report includes:
 29#     <enable-mathjax>true</enable-mathjax>
 30# this string will be substituted for {mathjax} in the `preamble`
 31mathjax = ('<script type="text/javascript" '
 32           'src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> '
 33           '</script>')
 34
 35# This text is the start of the generated report.
 36# This widgets follow on immediately.
 37# The following expansions are available:
 38#  {title}: If the report template includes a <title>, this expands to "<title>...</title>"
 39#    where "..." is the title string. If the report template has no title then {title} expands
 40#    to an empty string.
 41#  {STATIC_URL}: Base URL for internal static resources
 42#  {mathjax}: Contents of the mathjax variable if the template has enable-mathjax set
 43preamble = r"""<!doctype html>
 44<html>
 45<head>
 46    <meta charset="utf-8">
 47    <link rel="stylesheet" type="text/css" href="theme.css"/>
 48    <link rel="stylesheet" type="text/css" href="theme_print.css" media="print"/>
 49    <link rel="stylesheet" type="text/css" href="{STATIC_URL}3rdparty/fancybox/jquery.fancybox-1.3.4.css"/>
 50    <script type="text/javascript" src="{STATIC_URL}3rdparty/jquery-1.7.1.min.js"></script>
 51    <script type="text/javascript" src="{STATIC_URL}3rdparty/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
 52    <script>
 53    if (!window.jQuery) {{
 54        document.write('<script type="text/javascript" src="http://chart/s3/static/3rdparty/jquery-1.7.1.min.js"><\/script>');
 55        document.write('<script type="text/javascript" src="http://chart/s3/static/3rdparty/fancybox/jquery.fancybox-1.3.4.pack.js"><\/script>');
 56        document.write('<link rel="stylesheet" type="text/css" href="http://chart/s3/static/3rdparty/fancybox/jquery.fancybox-1.3.4.css" type="text/css"/>');
 57    }};
 58    </script>
 59    <script type="text/javascript" src="https://www.eumetsat.int/shared/assets/js/eum_fbdefs.js"></script>
 60{mathjax}    <script>
 61        var EPS_REP_CONFIG         = Array();
 62        EPS_REP_CONFIG['debug']    = 0;
 63        EPS_REP_CONFIG['hip-label']     = 'High Interest Parameters';
 64        EPS_REP_CONFIG['hip-hidden-id'] = 'slidingDiv';
 65
 66        /*Cache for hash anchors for page refresh jump*/
 67        var info_hidden_hash_divs = Array();
 68
 69        $(document).ready(function() {{
 70            $("a.fancybox").each(function() {{
 71                var a = this, live, rtitle, ltitle;
 72                a=$(a);
 73                if (a.data('livelink') !== undefined) {{
 74                    rtitle = '<a class="button" style="float:right" href="' + a.data('livelink') +
 75                        '" target="_blank">Live link</a>';
 76                }} else {{
 77                    rtitle = '';
 78                }}
 79                if (a.data('summarylink') !== undefined) {{
 80                    ltitle = '<a class="button" style="float:left" href="' + a.data('summarylink') +
 81                        '" target="_blank">Extended info</a>';
 82                }} else {{
 83                    rtitle = '';
 84                }}
 85                $(this).fancybox({{
 86                    'overlayShow': false,
 87                    'transitionIn': 'elastic',
 88                    'transitionOut': 'elastic',
 89                    'hideOnOverlayClick': true,
 90                    'hideOnContentClick': true,
 91                    'overlayShow': true,
 92                    'overlayColor': '#black',
 93                    'titlePosition': 'inside',
 94                    'titleFormat': function(title, currentArray, currentTitle, currentOpts) {{
 95                        return ltitle + title + rtitle;
 96                    }}
 97                }});
 98            }});
 99
100            // assign click event to all TOC entries that point to hidden sections
101            $('div.chart ol > li').each(function() {{
102                var li = $(this);
103                var compText = li.find('a')[0].text ? li.find('a')[0].text:li.find('a')[0].innerText;
104                if(EPS_REP_CONFIG['debug']) console.log("LI: "+compText);
105                if (compText == EPS_REP_CONFIG['hip-label']) {{
106                    if(EPS_REP_CONFIG['debug']) console.log("Found HIP");
107                        li.click(function(){{
108                            if(EPS_REP_CONFIG['debug'])console.log("Main Entry");
109                            $('.'+EPS_REP_CONFIG['hip-hidden-id']).show();
110                        }});
111
112                        li.find('ul > li > a').each(function() {{
113                            var atag = $(this);
114                            /*Save all affected hashes for page refresh*/
115                            info_hidden_hash_divs[atag.attr('href')] = atag.attr('href');
116                            if(EPS_REP_CONFIG['debug']) console.log("HIP Sub: "+atag.attr('href'));
117                            atag.click(function(){{
118                                if(EPS_REP_CONFIG['debug'])console.log("Entry: "+atag.attr('href'));
119                                $('.'+EPS_REP_CONFIG['hip-hidden-id']).show();
120                            }});
121                    }});
122                }}
123            }})
124
125            /*Init settings: IE, will not close it again when clicking a non-expandable TOC entry as IE does not actually refresh page*/
126            $('.'+EPS_REP_CONFIG['hip-hidden-id']).hide();
127
128            //Click event registration for the Normal HIP link
129            $('.showHide').click(function(){{
130                $('.'+EPS_REP_CONFIG['hip-hidden-id']).slideToggle();
131                var self = this;
132                if(EPS_REP_CONFIG['debug']) console.log("Toggling Slider: "+self.id);
133                if(self.id=="showHip"){{
134                    $("#showHip").hide();
135                }}else{{
136                    $("#showHip").show();
137                }}
138            }});
139
140            /*We must open the hidden HIP section when any of the
141            * TOC elements within Interest params are deeplinked*/
142            checkOpenDivAction();
143
144        }});
145
146        /*
147        If any registered unhiders are adding anchor to URL, a refresh will
148        check previous jQuery actions (array fill up) to respond by opening div.
149        */
150        function checkOpenDivAction() {{
151            /*Open hidden div if param was found as hash*/
152            //if(EPS_REP_CONFIG['debug'])console.log("Hash: '"+location.hash+"'");
153            if(location.hash == "#hiddenParams" || info_hidden_hash_divs[location.hash]) {{
154                console.log("Showing slidingDiv as of: "+location.hash);
155                $('.'+EPS_REP_CONFIG['hip-hidden-id']).show();
156            }}
157        }}
158    </script>
159{title}</head>
160<body>
161<div class="chart">
162"""
163
164
165# This text is copied to the end of the report after all widgets.
166postscript = """
167<p class="postscript">This report was generated on {{gentime}} by {appname} using
168template {{template}} and SRDB {{srdb}}.</p>
169</div>
170</body>
171</html>
172""".format(appname=settings.APPNAME)
173
174
175def mod_filename(document, base):
176    """Generate a unique filename based on `base`.
177    `scid`, `sensing_start` and `sensing_stop` may be used:
178
179    >>> mod_filename(document, 'NEDT_H1.png')
180    'MWR_M02_2012_180_NEDT_H1.png'
181
182    This is used to assign names to the resources (images) within the report.
183    It is basically needed because Oracle UCS requires globally unique filenames for everything
184    because it doesn't have a concept like "directories".
185    """
186
187    if document.template.prefix is None:
188        prefix = '{{initials}}_{{scid}}_{{year}}_{{doy}}'
189
190    else:
191        prefix = document.template.prefix
192
193    if 'sensing_start' in document.config:
194        start = document.config['sensing_start']
195        isoyear, isoweek = start.isocalendar()[0:2]
196        shortyear = start.strftime('%y')
197        doy = start.strftime('%j')
198
199        if (document.config['sensing_stop'] - document.config['sensing_start']) > timedelta(days=100):
200            isoyear = start.year
201            if start.month < 6 and isoweek > 20:
202                isoweek = 1
203
204        isoweek = '{week:02}'.format(week=isoweek)
205
206    else:
207        start = datetime(2000, 1, 1)
208        isoyear = 'x'
209        isoweek = 'x'
210        shortyear = 'x'
211        doy = 'x'
212
213    if document.title is None:
214        title = 'RPT'
215
216    else:
217        title = document.title
218
219    initials = ''.join(word[0].upper() for word in title.split())
220
221    scid = document.config.get('scid', 'x')
222
223    sat_acronym = {'M02': 'MA',
224                   'M01': 'MB',
225                   'M03': 'MC'}.get(scid, 'Mx')
226
227    prefix = Template(prefix).render(Context({
228                'scid': scid,
229                'sat_acronym': sat_acronym,
230                'report': title,
231                'initials': initials,
232                'isoyear': isoyear,
233                'year': isoyear,
234                'isoweek': isoweek,
235                'week': isoweek,
236                'shortyear': shortyear,
237                'doy': doy,
238                'start': start}))
239
240    result = Path('{prefix}_{base}'.format(prefix=prefix, base=base))
241    # logging.debug('mod_filename result {path}'.format(path=result))
242    return result