import datetime
from plyer import notification
from psql import query


def find_expiring_meds(date_today):
    """
    Input: Date
    Checks all medicaments in the table meds whether they expire
    one day after the input date.
    Output: List with expiring medicaments
    """
    all_meds = query("SELECT * FROM meds") #query the psql table 'meds'
    date_tmrw = date_today + datetime.timedelta(days=1) #add one day to the input date
    expiring_meds = []
    for item in all_meds:
        #checks if the expiration date is before the day after the input date
        if item[4] <= date_tmrw:
            expiring_meds.append(item)
    return expiring_meds


def send_notification(expiring_meds):
    """
    Input: List with expiring medicaments
    Sends a notification to each user that has expiring medicaments and advises
    which medicaments expire, how to dispose them and how to reorder them.
    Output: None
    """
    if len(expiring_meds) > 0:
        message_dict = {}
        for item in expiring_meds:
            #if the user is already in the message_dict
            if item[1] in message_dict.keys():
                value = message_dict[item[1]]
                message_dict[item[1]] = value + " , " + item[2]
            else:
                message_dict[item[1]] = item[2]
        title="Some of your Medicines expire tomorrow!"
        for key, value in message_dict.items():
            message = "Hi {}. Following medicaments expire tomorrow: {}. You can return expired and unused drugs to a pharmacy. To reorder open your MediBox-App.".format(key, value)
            notification.notify(title=title,
                                            message=message,
                                            app_icon=None,
                                            timeout=5,
                                            toast=False)


date_today = datetime.datetime(2022, 1, 31).date()
send_notification(find_expiring_meds(date_today))
