#!/usr/bin/python3
#
# Copyright (c) Daniel Sheffield 2021 - 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
from psycopg import Cursor
from urwid import raw_display, WidgetPlaceholder, SolidFill, MainLoop
from app.activities.ActivityManager import ActivityManager, show_or_exit
from app.activities.PriceCheck import PriceCheck
from app.data.QueryManager import QueryManager, display_mapper
from app.palette import high_contrast

try:
    from db_credentials import HOST, PASSWORD
    host = f'host={HOST}'
    password = f'password={PASSWORD}'
except:
    host = ''
    password = ''

try:
    import os

    import psycopg
    user = os.getenv('USER')
    conn = psycopg.connect(f"{host} dbname=grocery user={user} {password}")
    cur: Cursor = conn.cursor()
except:
    print('Failed to set up db connection. Entering Mock mode')
    exit(1)
    #from mock import *

class GroceryPriceCheck(WidgetPlaceholder):
    def __init__(self, activity_manager):
        super().__init__(SolidFill(u'/'))
        self.activity_manager = activity_manager
        price_check = self.activity_manager.get('price_check')

        self.activity_manager.show(self)
        self.activity_manager.show(price_check)

cur.execute("BEGIN")

activity_manager = ActivityManager()
query_manager = QueryManager(cur, display_mapper)

activity_manager.create(PriceCheck, 'price_check',
    activity_manager, query_manager
)

app = GroceryPriceCheck(activity_manager)

def iter_palettes():
    palettes = [ v for k,v in high_contrast.theme.items() ]
    while True:
        p = palettes.pop(0)
        palettes.append(p)
        yield p

palettes = iter_palettes()

screen = raw_display.Screen()
loop = MainLoop(app, next(palettes), screen=screen,
        unhandled_input=lambda k: show_or_exit(k, screen=screen, palettes=palettes),
        pop_ups=True)
loop.run()

cur.close()
conn.close()
