import streamlit as st
import pandas as pd
import argparse
import datetime as dt
from sqlmodel import create_engine, Session

parser = argparse.ArgumentParser(description="A steamlit dashboard for visualising news analytics.")
parser.add_argument("--database", type=str, default="sqlite:///database.db")

class Dasboard:
    def __init__(self, database) -> None:
        self.engine = create_engine(database)
        self.attr = {
            "date_range": self.get_date_range(),
        }
        self.state = st.session_state
        self.build()


    def build(self):

        # ~~~ Build Sidebar ~~~~~~~~~
        st.sidebar.header("Newsreader")

        with st.form(key="date_picker"):
            st.sidebar.date_input(
                "Period From",
                key="period_from",
                min_value=self.attr["date_range"][0],
                max_value=self.attr["date_range"][1],
                value=self.attr["date_range"][0]
            )
            st.sidebar.date_input(
                "Period To",
                key="period_to",
                min_value=self.attr["date_range"][0],
                max_value=self.attr["date_range"][1],
                value=self.attr["date_range"][1]
            )

        # ~~~ Build Main UI ~~~~~~~~~~

        st.text_input("Search", key="search_text")

        st.write(self.state.search_text)
        st.write([self.state.period_from, self.state.period_to])
        st.write(self.get_total_sentiment("00375cd420e37d4084c6668975f91648"))


    # ~~~ Callbacks ~~~~~~~~~~~
        

    # ~~~ Analytics Operations ~~~~~~
    def exec(self, stmt: str, params = {}):
        with Session(self.engine) as session:
            return session.exec(stmt, params=params).all()

    def get_date_range(self):
        ans = self.exec("""
            SELECT MIN(date) as first_date, MAX(date) as last_date FROM document
        """)
        return list(map(dt.datetime.fromisoformat, ans[0]))

    def get_total_sentiment(self, document_id: str):
        ans = self.exec("""
            WITH t1 AS (
                SELECT 
                document.id as document_id, 
                paragraph.sentiment as sent,  
                COUNT(*) as paragraphs
                FROM document
                JOIN paragraph ON document.id = paragraph.document_id
                WHERE document.id = :document_id
                GROUP BY document.id, paragraph.sentiment
            )
            SELECT sent, paragraphs FROM t1
        """, params={ "document_id": document_id })
        return pd.DataFrame(ans, columns=["lable", "total_paragraphs"])
  

if __name__ == "__main__":
    args = parser.parse_args()
    dashboard = Dasboard(args.database)
    

pandas.DataFrame streamlit.form streamlit.text_input streamlit.sidebar.header sqlmodel.create_engine argparse.ArgumentParser sqlmodel.Session streamlit.write streamlit.sidebar.date_input
[((135, 231), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""A steamlit dashboard for visualising news analytics."""'}), "(description=\n    'A steamlit dashboard for visualising news analytics.')\n", (158, 231), False, 'import argparse\n'), ((385, 408), 'sqlmodel.create_engine', 'create_engine', (['database'], {}), '(database)\n', (398, 408), False, 'from sqlmodel import create_engine, Session\n'), ((619, 650), 'streamlit.sidebar.header', 'st.sidebar.header', (['"""Newsreader"""'], {}), "('Newsreader')\n", (636, 650), True, 'import streamlit as st\n'), ((1282, 1324), 'streamlit.text_input', 'st.text_input', (['"""Search"""'], {'key': '"""search_text"""'}), "('Search', key='search_text')\n", (1295, 1324), True, 'import streamlit as st\n'), ((1334, 1366), 'streamlit.write', 'st.write', (['self.state.search_text'], {}), '(self.state.search_text)\n', (1342, 1366), True, 'import streamlit as st\n'), ((1375, 1431), 'streamlit.write', 'st.write', (['[self.state.period_from, self.state.period_to]'], {}), '([self.state.period_from, self.state.period_to])\n', (1383, 1431), True, 'import streamlit as st\n'), ((2549, 2605), 'pandas.DataFrame', 'pd.DataFrame', (['ans'], {'columns': "['lable', 'total_paragraphs']"}), "(ans, columns=['lable', 'total_paragraphs'])\n", (2561, 2605), True, 'import pandas as pd\n'), ((665, 691), 'streamlit.form', 'st.form', ([], {'key': '"""date_picker"""'}), "(key='date_picker')\n", (672, 691), True, 'import streamlit as st\n'), ((705, 880), 'streamlit.sidebar.date_input', 'st.sidebar.date_input', (['"""Period From"""'], {'key': '"""period_from"""', 'min_value': "self.attr['date_range'][0]", 'max_value': "self.attr['date_range'][1]", 'value': "self.attr['date_range'][0]"}), "('Period From', key='period_from', min_value=self.attr\n    ['date_range'][0], max_value=self.attr['date_range'][1], value=self.\n    attr['date_range'][0])\n", (726, 880), True, 'import streamlit as st\n'), ((977, 1148), 'streamlit.sidebar.date_input', 'st.sidebar.date_input', (['"""Period To"""'], {'key': '"""period_to"""', 'min_value': "self.attr['date_range'][0]", 'max_value': "self.attr['date_range'][1]", 'value': "self.attr['date_range'][1]"}), "('Period To', key='period_to', min_value=self.attr[\n    'date_range'][0], max_value=self.attr['date_range'][1], value=self.attr\n    ['date_range'][1])\n", (998, 1148), True, 'import streamlit as st\n'), ((1650, 1670), 'sqlmodel.Session', 'Session', (['self.engine'], {}), '(self.engine)\n', (1657, 1670), False, 'from sqlmodel import create_engine, Session\n')]