#
# Copyright (c) Daniel Sheffield 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
from datetime import date, datetime
import os
import sys
from psycopg import connect, Cursor
import seaborn as sns
from db_credentials import HOST, PASSWORD
from app.activities.Plot import (
    get_data,
    get_input,
    pivot_data,
    pie,
    line,
)
from app.data.QueryManager import QueryManager, display_mapper

ALL_UNITS = {'g','kg','mL','L','Pieces','Bunches','Bags'}
host = f'host={HOST}'
password = f'password={PASSWORD}'
user = os.getenv('USER')
conn = connect(f"{host} dbname=grocery user={user} {password}")
cur: Cursor = conn.cursor()
cur.execute("BEGIN")

query_manager = QueryManager(cur, display_mapper)

fields = get_input(query_manager, ALL_UNITS)

unit = fields['unit'] = fields['unit'] or 'kg'
fields = { k: v or None for k,v in fields.items() }
if unit not in ALL_UNITS:
    print(f'Invalid unit: {unit}')
    exit(2)

print('Getting data for selection:\n  ')
print('\n  '.join([
    f'{k.title()}: {v}' for k,v in fields.items()
]))

data = get_data(query_manager, **fields)
if data.empty:
    sys.exit(1)

now = datetime.now().date()
pivot = pivot_data(data[data['ts_month'] == date(now.year,now.month,1)])

sns.set_theme()

if not pivot.empty:
    pie(pivot, col='quantity', title=f'Quantity ({unit})')
    pie(pivot, col='price', title='Price ($)')

pivot = data.pivot_table(index=['ts_raw',], columns=['product',], values=['$/unit'], aggfunc='mean')
pivot.columns = pivot.columns.droplevel()
print(pivot.info())
print(pivot)

line(pivot, xlabel='Time', ylabel=f'$ / {unit}')