#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import logging
import logging.config
import socket
import os.path as path
from pathlib import Path, PosixPath

import dash
import dash_auth
import dash_core_components as dcc
import dash_html_components as html
from flask_talisman import Talisman
from webviz_config.common_cache import cache
from webviz_config.webviz_store import webviz_storage
from webviz_config.webviz_assets import webviz_assets
{% for module in _imports %}
{%- if module is string -%}
import {{ module }}
{%- else -%}
import {{ module[0] }} as {{ module[1] }}
{%- endif %}
{% endfor %}


logging.getLogger('werkzeug').setLevel(logging.WARNING)

logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {'default': {
        'format': ' webviz log [%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        'datefmt': '%Y-%m-%d %H:%M:%S'
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})

app = dash.Dash(__name__, external_stylesheets={{ external_stylesheets }})
server = app.server

app.title = '{{ title }}'
app.config.suppress_callback_exceptions = True

app.webviz_settings = {
    'portable': {{ portable }},
    'plotly_layout': {{ plotly_layout }}
                      }

cache.init_app(server)

CSP = {{ csp }}
FEATURE_POLICY = {{ feature_policy }}

Talisman(server, content_security_policy=CSP, feature_policy=FEATURE_POLICY)

webviz_storage.use_storage = {{ portable }}
webviz_storage.storage_folder = path.join(path.dirname(path.realpath(__file__)),
                                          'webviz_storage')

webviz_assets.portable = {{ portable }}
{{ 'webviz_assets.register_app(app)' if not portable else ''}}

app.layout = dcc.Tabs(parent_className="layoutWrapper",
                      content_className='pageWrapper',
                      vertical=True, children=[
   {% for page in pages %}
    dcc.Tab(
        {%- if loop.first -%}
            id='logo',
            className='styledLogo',
        {%- else -%}
            {%- if loop.last -%}
                id='last_page',
            {%- else -%}
                id='{{page.id}}',
            {%- endif -%}
            label='{{page.title}}',
            selected_className='selectedButton',
            className='styledButton',
        {%- endif -%}
            children=[
                 {% for content in page.content -%}
                  {%- if content is string -%}
                    dcc.Markdown(r'''{{ content }}''')
                  {%- else -%}
                    {{ content._call_signature[0] }}.{{ content._call_signature[1] }}
                  {%- endif -%}
                  {{- '' if loop.last else ','}}
                 {% endfor -%}
                 ]
    ){{- '' if loop.last else ',' -}}
  {% endfor %}]
)

if __name__ == '__main__':
    # This part is ignored when the webviz app is started
    # using Docker container and uwsgi (e.g. when hosted on Azure).

    dash_auth.BasicAuth(app, {'{{ username }}': '{{ password }}'})
    app.run_server(host={{ "'localhost'" if localhostonly else 'socket.getfqdn()'}}, port={{port}}, ssl_context={{ssl_context}}, debug=False, use_reloader=True, dev_tools_hot_reload=True, dev_tools_hot_reload_interval=1.0)
