"""

"""

#%%
from pathlib import Path
import sys

# path = "/home/user/PythonProj/simple-report/simple_report/"
# sys.path.insert(0, path)
path = "/home/user/PythonProj/simple-report/"
sys.path.insert(0, path)

import datetime
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px

# from simple_report.utils.utils import plot_360_n0sc0pe
# from simple_report.core.components.base import BaseElement
# from simple_report.core.components.text import H1, H2, H3, List, P
# from simple_report.core.components.plot import Plot
# from simple_report.core.components.table import Table
# from simple_report.core.components.row import Row
# from simple_report.core.components.collapse import Collapse
# from simple_report.core.components.tabs import Tabs
# from simple_report.core.components.modal import Modal
# from simple_report.core.report import HtmlReport



# from altair.vegalite.v4.api import Chart

# import datapane as dp

#%%

# ########################################################
# Demonstrations
# ########################################################

def create_finance_report_demo():
    # Creating data for the report (tables, texts, plots...)
    current_time = datetime.datetime.now()
    current_time_str = current_time.strftime("%Y-%m-%d_%H-%M-%S")
    report_directory = f"report_{current_time_str}"

    # Load historical data in the past 10 years
    sp500_history = pd.read_csv('/home/user/PythonProj/simple-report/simple_report/fin_data.csv')

    # Remove unnecessary columns
    sp500_history = sp500_history#.drop(columns=['Dividends', 'Stock Splits'])

    # Create a new column as Close 200 days moving average
    sp500_history['Close_200ma'] = sp500_history['Close'].rolling(200).mean()

    # Create a summary statistics table
    sp500_history_summary = sp500_history.describe()

    # Create a veeeery wide table
    sp500_wide_table = pd.concat([sp500_history_summary]*5, axis=1)

    fig1, ax1 = plt.subplots(figsize=(10, 6))
    fig1 = sns.relplot(data=sp500_history[['Close', 'Close_200ma']], kind='line', height=3, aspect=2.0)

    fig2, ax2 = plt.subplots(figsize=(10, 6))
    sns.histplot(data=sp500_history['Volume'], ax=ax2)

    # https://plotly.com/python-api-reference/generated/plotly.io.to_html.html
    lineplot1 = px.line(sp500_history, y="Close")


    page_names = ['Home', 'Data']
    report_title = 'My report'

    html = HtmlReport(
        report_title=report_title,
        project_name='FinanceReport',
        # author='Douglas Macedo Sgrott',
        pages=page_names,
        background_color='#f47d30'
        )

    html.add(H1('Daily S&P 500 prices report', id='foo'))
    html.add(Tabs(content={
        'Home': P('Home'),
        'Menu 1': P('Menu 1'),
        'Menu 2': P('Menu 2'),
        },
        use_tabs=True
    ))
    html.add(List(text_list="This is a simple list"))
    html.add(Tabs(content={
        'Home': P('Home'),
        'Menu 1': P('Menu 1'),
        'Menu 2': P('Menu 2'),
        },
        use_tabs=False
    ))
    html.add(P('Daily S&P 500 prices report'))
    html.add(P("This is a more complex list:"))
    html.add(List(text_list=["Banana", "Apple", "Orange"]))
    html.add(Collapse(
        use_panel=False,
        toggle_text='Toggle button',
        content=P('This is the content of the toggle button.')
    ))
    html.add(Row(
            P('This is on the left side.'),
            P('This is on the right side.')
        )
    )
    html.add(Collapse(
        use_panel=True,
        toggle_text='Toggle Panel',
        content=P('This is the content of the toggle button.')
    ))

    html.add(Modal(
        toggle_text='Modal',
        content=P('This is the content of the modal.')
    ))

    html.add(Modal(
        toggle_text='Modal',
        content=[
            P('This is the content #1 of the modal.'),
            P('This is the content #2 of the modal.'),
            P('This is the content #3 of the modal.'),
            P('This is the content #4 of the modal.'),
        ]
    ))

    html.add(H2('Historical prices of S&P 500'), page='Data')
    html.add(Table(dataframe=sp500_history.head(), title="This is a table title", use_striped_style=True), page='Data')
    html.add(Table(dataframe=sp500_history.head(), use_jquery=True), page='Data')
    html.add(Table(dataframe=sp500_history.tail(3)), page='Data')
    html.add(H2('Historical prices summary statistics'), page='Data')
    html.add(Table(dataframe=sp500_history_summary, title='Summary statistics'), page='Data')
    html.add(Table(dataframe=sp500_wide_table, title='A veeeeeery wide table', caption='This is a caption. This table was generated by repeatedly and horizontally concatenating a table several times.'), page='Data')

    html.add_new_page('Plots')
    html.add(Plot(figure=fig1, id='plot1'), page='Plots')
    html.add(Plot(figure=ax2), page='Plots')
    html.add(Plot(figure=lineplot1), page='Plots')


    os.makedirs(f"{report_directory}", exist_ok=True)
    html.export(report_directory)


# def create_finance_datapane_demo():
#     # Creating data for the report (tables, texts, plots...)
#     current_time = datetime.datetime.now()
#     current_time_str = current_time.strftime("%Y-%m-%d_%H-%M-%S")
#     report_directory = f"report_{current_time_str}"

#     # Load historical data in the past 10 years
#     sp500_history = pd.read_csv('./fin_data.csv')

#     # Remove unnecessary columns
#     sp500_history = sp500_history#.drop(columns=['Dividends', 'Stock Splits'])

#     # Create a new column as Close 200 days moving average
#     sp500_history['Close_200ma'] = sp500_history['Close'].rolling(200).mean()

#     # Create a summary statistics table
#     sp500_history_summary = sp500_history.describe()

#     # Create a veeeery wide table
#     sp500_wide_table = pd.concat([sp500_history_summary]*5, axis=1)

#     fig1, ax1 = plt.subplots(figsize=(10, 6))
#     fig1 = sns.relplot(data=sp500_history[['Close', 'Close_200ma']], kind='line', height=3, aspect=2.0)

#     fig2, ax2 = plt.subplots(figsize=(10, 6))
#     sns.histplot(data=sp500_history['Volume'], ax=ax2)

#     # https://plotly.com/python-api-reference/generated/plotly.io.to_html.html
#     lineplot1 = px.line(sp500_history, y="Close")


#     report = dp.Report(
#         dp.Page(title="Home",
#                 blocks=[
#                     dp.Text("# Daily S&P 500 prices report"),
#                     dp.Text("This is a simple list"),
#                     dp.Text("Daily S&P 500 prices report"),
#                     dp.Text("This is a more complex list:"),
#                     # dp.List(["Banana", "Apple", "Orange"]),
#                 ]),
#         dp.Page(title="Dataset",
#                 blocks=[
#                     dp.Text("## Historical prices of S&P 500"),
#                     dp.DataTable(sp500_history.head()),
#                     dp.Table(sp500_history.head()),
#                     dp.Text("## Historical prices summary statistics"),
#                     dp.DataTable(sp500_history_summary),
#                     # dp.DataTable(sp500_wide_table),
#         ]),
#         dp.Page(title="Plots",
#                 blocks=[
#                     dp.Plot(ax1),
#                     dp.Plot(ax2),
#                     # dp.Plot(fig1),
#                     # dp.Plot(fig2),
#                     dp.Plot(lineplot1),
#         ]),
#     )
#     report.save(path="Complex_layout.html", open=True)


# def create_dp_report1_demo():

#     import pandas as pd
#     import altair as alt
#     import datapane as dp

#     current_time = datetime.datetime.now()
#     current_time_str = current_time.strftime("%Y-%m-%d_%H-%M-%S")
#     report_directory = f"report_{current_time_str}"


#     df = pd.read_csv('https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv')
#     countries = ['United Kingdom', 'Germany', 'France']
#     subset = df[df.location.isin(countries)]

#     base = alt.Chart(subset).encode(
#         x='date:T',
#         color='location'
#     ).mark_line(
#         size=5,
#         opacity=0.75, 
#     ).interactive()

#     plots = [
#     base.encode(y='total_vaccinations_per_hundred'), 
#     base.encode(y='daily_vaccinations_per_million'),
#     base.encode(y='people_vaccinated')
#     ]

#     html = HtmlReport(
#         report_title="Report 1 from Datapane's tutorial",
#         project_name='SimpleReport',
#         author='Douglas Macedo Sgrott',
#         background_color='#f47d30'
#         )
    
#     html.add_h2(text=f"Covid vaccinations in {', '.join(countries)}")
#     html.add_plot(figure=plots[0])
#     html.add_plot(figure=plots[1])
#     html.add_plot(figure=plots[2])
#     html.add_table(dataframe=subset, title=f"Dataset for {countries}")

#     os.makedirs(f"{report_directory}", exist_ok=True)
#     html.export(report_directory)
#     # report = dp.Report(
#     #     dp.Text(f"## Covid vaccinations in {', '.join(countries)}"),
#     #     dp.Group(*plots[:2], columns=2),
#     #     plots[2],
#     #     dp.DataTable(subset, caption=f'Dataset for {countries}'),
#     # )

#     # report.publish(name='My Covid Report', open=True)


if __name__ == "__main__":
    create_finance_report_demo()
    # create_finance_datapane_demo()
    # create_dp_report1_demo()
    
    print("EOL")
