import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
from de import load
import vizro.models as vm
from vizro.models.types import capture
# Sample data_dict where each key has time series data
import vizro as vz
from glob import glob
def ftext(text):
    text = text.replace('data/', '').replace('.csv', '')
    name = '_'.join(text.split('_')[:2])
    end_date = text.split('_')[-1]
    return name, end_date
def load():
    csvs = glob('data/*.csv')
    data_dict = {}
    for csv in csvs:
        name, end_date = ftext(csv)
        key = name + '_' + end_date
        df = pd.read_csv(csv)
        df['name'] = name
        df['Local Time'] = pd.to_datetime(df['Local Time'])
        data_dict[key] = df
    return data_dict
# Load the data (assuming your data loading logic stays the same)
#data_dict = load()
df = pd.read_csv('data/df_combined.csv')
df['Local Time'] = pd.to_datetime(df['Local Time'])
df['Hour'] = df['Local Time'].dt.hour
# Define the function for creating the line plot
@capture("graph")
def create_lineplot(data_frame, **kwargs):
    data_frame = data_frame.loc[
        pd.notnull(data_frame["Gas Consumption (l)"])
    ].sort_values("Local Time")
    fig = go.Figure()
    for name in data_frame['name'].unique():
        df = data_frame.loc[data_frame['name'] == name]
        # Create the line plot
        fig.add_trace(
            go.Scatter(
                    x=df["Local Time"],
                    y=df["Gas Consumption (l)"],
                    mode="lines+markers",
                hovertemplate="Time %{x}><br>Consumption: %{y}<extra></extra>",
                name=name,
                )
        )
    # Customize the layout
    fig.update_layout(
        title=f"Gas Accumulation over Time",
        xaxis_title="Local Time",
        yaxis_title="Gas Consumption (l)",
    )
    return fig
# Define the function for creating the ideal gas plot
@capture("graph")
def create_ideal_gas_plot(data_frame):
    data_frame = data_frame.loc[data_frame['Flow (lph)'] > 0]
    fig = go.Figure()
    for name in data_frame['name'].unique():
        df = data_frame.loc[data_frame['name'] == name]
        fig.add_trace(
            go.Scatter(
                x=df["Pressure (Pa)"],
                y=df["Flow (lph)"],
                mode="markers",
                customdata=df["Temperature (°C)"],
                hovertemplate="Temp %{customdata}><extra></extra>",
                name=name,
                marker=dict(
                    opacity=0.5,
                )
            )
        )
    fig.update_layout(
        title=f"Ideal Gas Diagnosis",
        xaxis_title="Pressure",
        yaxis_title="Flow (lph)",
    )
    return fig
@capture("graph")
def create_hourly_hist(data_frame):
    hourly_df = pd.pivot_table(data_frame, index=['Hour', "name"], values='Flow (lph)', aggfunc="sum").reset_index()
    fig = go.Figure()
    for name in hourly_df['name'].unique():
        df = hourly_df.loc[hourly_df['name'] == name]
        fig.add_trace(
            go.Bar(
                x=df['Hour'], 
                y=df['Flow (lph)'],
            name=name)
        )
    fig.update_layout(
        title=f"Flow by hour of day",
        xaxis_title="Hour",
        yaxis_title="Flow (lph)",
    )
    return fig
    
page = vm.Page(
    title="Graphs",
    id="chart",
    components=[
        vm.Graph(
            figure=create_lineplot(
                data_frame=df,
            ),
            title="Basic",
        ),
        vm.Graph(figure=create_ideal_gas_plot(df)),
        vm.Graph(figure=create_hourly_hist(df))
    ],
    controls=[
        vm.Filter(
            column="name",
            selector=vm.Dropdown(title="Farmer",
                value=['Eipparla_Bharti'],
                                )
        ),
    ],
)
# Define the Vizro components and the page
dashboard = vm.Dashboard(title="Gas Consumption Dashboard", pages=[page])
print('hi')
def get_dash():
    return dashboard
# Run the Vizro dashboard
app = get_dash
vz.Vizro().build(dashboard).run()
if __name__ == "__main__":
    vz.Vizro().build(dashboard).run()