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


import socket
import dash
import dash_auth
import dash_core_components as dcc
import webviz_components as webviz
import os.path as path
from pathlib import Path, PosixPath
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 %}

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

app.title = '{{ title }}'
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.config.suppress_callback_exceptions = True

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 = webviz.Layout(children=[
   {% for page in pages %}
    webviz.Page(
        id='{{ page.id }}',
        title='{{ page.title }}',
        children=[
                 {% for content in page.content -%}
                  {%- if content is string -%}
                    dcc.Markdown(r'''{{ content }}''')
                  {%- else -%}
                    {{ content._call_signature }}.layout
                  {%- 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=True' if debug else 'dev_tools_hot_reload=True'}})
