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

# AUTOMATICALLY MADE FILE. DO NOT EDIT.
# This file was generated by {{ author }} on {{ current_date }}.

import logging
import threading
import datetime
from pathlib import Path, PosixPath, WindowsPath

import dash
import dash_core_components as dcc
import dash_html_components as html
from flask_talisman import Talisman
import webviz_config
import webviz_config.certificate
from webviz_config.themes import installed_themes
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 %}

# We do not want to show INFO regarding werkzeug routing as that is too verbose,
# however we want other log handlers (typically coming from webviz plugin dependencies)
# to be set to user specified log level.
logging.getLogger("werkzeug").setLevel(logging.WARNING)
logging.getLogger().setLevel(logging.{{ loglevel }})

theme = webviz_config.WebvizConfigTheme("{{ theme_name }}")
theme.from_json((Path(__file__).resolve().parent / "theme_settings.json").read_text())

app = dash.Dash(
    __name__,
    external_stylesheets=theme.external_stylesheets,
    meta_tags=[
        {"name": "viewport", "content": "width=device-width, initial-scale=1"}
    ],
)
app.logger.setLevel(logging.WARNING)
server = app.server

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

app.webviz_settings = {
    "shared_settings": webviz_config.SHARED_SETTINGS_SUBSCRIPTIONS.transformed_settings(
        {{ shared_settings }}, {{ config_folder }}, {{ portable }}
    ),
    "portable": {{ portable }},
    "theme": theme,
}

CACHE.init_app(server)

theme.adjust_csp({"script-src": app.csp_hashes()}, append=True)
Talisman(server, content_security_policy=theme.csp, feature_policy=theme.feature_policy)

WEBVIZ_STORAGE.use_storage = {{portable}}
WEBVIZ_STORAGE.storage_folder = Path(__file__).resolve().parent / "webviz_storage"

WEBVIZ_ASSETS.portable = {{ portable }}

if {{ not portable }} and not webviz_config.is_reload_process():
    # When Dash/Flask is started on localhost with hot module reload activated,
    # we do not want the main process to call expensive component functions in
    # the layout tree, as the layout tree used on initialization will anyway be called
    # from the child/restart/reload process.
    app.layout = html.Div()
else:
    app.layout = dcc.Tabs(
        parent_className="layoutWrapper",
        content_className="pageWrapper",
        className="sideBar",
        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 %}],
    )

{{ "WEBVIZ_ASSETS.directly_host_assets(app)" if not portable else ""}}

if __name__ == "__main__":
    # This part is ignored when the webviz app is started
    # using Docker container and uwsgi (e.g. when hosted on Azure).
    #
    # It is used only when directly running this script with Python,
    # which will then initialize a localhost server.

    port = webviz_config.utils.get_available_port(preferred_port=5000)

    token = webviz_config.LocalhostToken(app.server, port).one_time_token
    webviz_config.utils.LocalhostOpenBrowser(port, token)

    webviz_config.utils.silence_flask_startup()

    app.run_server(
        host="localhost",
        port=port,
        ssl_context=webviz_config.certificate.LocalhostCertificate().ssl_context,
        debug=False,
        use_reloader={{not portable}},
        dev_tools_prune_errors=False,
      {% if not portable -%}
        dev_tools_hot_reload=True,
        dev_tools_hot_reload_interval=1.0,
        dev_tools_silence_routes_logging=False,
      {% endif %}
    )
