#
# Copyright (c) 2015-2021 LabKey Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# ********************************
# This example demonstrates rendering a Dash Table via a LabKey Proxy Servlet.
# Prerequisites:
# 1. Proxy servlet named "dash"
# 2. Adjust container path, schema and table below
# Note: This example will not run using the default Dash
# development server URL. Instead, log into LabKey and
# navigate via the Proxy you set up (prerequisite #1) e.g.
# http://localhost:8080/labkey/_proxy/dash.

import dash
import dash_html_components as html
import dash_table

import pandas as pd
from labkey.api_wrapper import APIWrapper
from flask import request

from labkey.api_wrapper import APIWrapper
from labkey.exceptions import RequestError

# Header passed by LabKey Server containing the API Key for the user making the request
API_KEY = "X-Lkproxy-Apikey"

# This depends on server configuration, it is commonly "labkey" on a dev machine
# and "None" on a hosted or production server. If you are unsure of the value
# contact your administrator.
CONTEXT_PATH = "labkey"
# The domain name your LabKey server is running on
DOMAIN = "localhost:8080"
# Set to True if your server is using HTTPS
USE_SSL = False

CONTAINER_PATH = "Tutorials/HIV Study"
SCHEMA = "study"
QUERY = "Demographics"

# method is called by Dash via app.layout.
def serve_layout():
    # Dash doesn't always call serve_layout within a request context, so we need to check
    if request:
        api_key = request.headers.get(API_KEY)

        # If the user accesses dash directly we won't have the labkey headers
        if api_key:
            api = APIWrapper(
                DOMAIN,
                CONTAINER_PATH,
                context_path=CONTEXT_PATH,
                use_ssl=USE_SSL,
                api_key=api_key,
                # CSRF not needed when using API keys
                disable_csrf=True,
            )
            result = api.query.select_rows(SCHEMA, QUERY)
            df = pd.DataFrame(result["rows"])

            return html.Div(
                children=[
                    dash_table.DataTable(
                        id="datatable-paging",
                        columns=[{"name": i, "id": i} for i in df.columns],
                        data=df.to_dict("records"),
                    )
                ]
            )

    # Not a proxied call, serve a default layout
    return html.Div(children=[html.Div(children="LabKey Dash Table Example")])


pd.options.display.float_format = "{:,.2f}".format
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# Update Dash config so it generates paths relative to LabKey's proxy server path

app.config.update(
    {
        "routes_pathname_prefix": "./",
        "requests_pathname_prefix": "./",
    }
)


app.layout = serve_layout
port = 8050

if __name__ == "__main__":
    app.run_server(debug=True, port=port)


