from datetime import datetime as dt
import logging
import os

import simplematrixbotlib as botlib

from .db import Data

MODULE='shop'

DATE_FORMAT = '%Y-%m-%d'

def today():
    return dt.now().strftime(DATE_FORMAT)

PREFIX = f'!{MODULE}'
logger = logging.getLogger(__name__)
logging.basicConfig(filename=f'{MODULE}.log', encoding='utf-8', level=logging.DEBUG)
logging.getLogger('nio').setLevel(logging.WARNING)

async def do_shop(match):
    '''
    Prefix: !shop

    Synax:
      !shop COMMAND ARGS

    Commands:
      help - show this help
      extra.help - show extended help
      add  - add an item to shop for
      add.store - add a store
      assign ITEM_ID - assign item to last used store id
      buy - mark item as purchased
      clear STORE_ID - clear all purchased items for STORE_ID from database
      list - re-show list from last used store
      stores - list all stores
      shop.at STORE_ID - list all items assigned to store and use this store for future commands
    '''
    extended_help = '''
      assign.item.to.store ITEM_ID STORE_ID - plan to shop for at store for item
      clear.all STORE_ID - clear **all** items for STORE_ID from database
      remove.item ITEM_ID - remove a shopping item from the datatbase
      remove.store STORE_ID - remove a store from the datatbase (requires clearing the list first)
      setup - run one time database setup
      unsorted - list all items not assigned to any store

    '''

    if match.command('setup'):
        result = Data().setup()
        return [result]

    if match.command('stores'):
        items = Data().get_stores()
        results = ['List of Stores']
        for item in items:
            results.append(str(item))
        return results

    if match.command('add'):
        new = ' '.join(match.args()[1:])
        result = Data().add_item(new)
        results = [f'Item added with id {result}']
        for item in Data().get_last_shopping_list():
            results.append(str(item))
        return results

    if match.command('add.store'):
        new = ' '.join(match.args()[1:])
        result = Data().add_store(new)
        return [f'Store added with id {result}']

    if match.command('assign.item.to.store'):
        item_id  = int(match.args()[1])
        store_id = int(match.args()[2])
        Data().assign_store(item_id, store_id)
        return ['Success']

    if match.command('assign'):
        item_id  = int(match.args()[1])
        Data().assign_last_store(item_id)

        # Now print the list for the assigned store
        items = Data().get_last_shopping_list()
        results = ['Shopping List']
        for item in items:
            results.append(str(item))
        return results

    if match.command('buy'):
        item_id = ' '.join(match.args()[1:])
        Data().purchase_item(item_id)
        return ['Success']

    if match.command('clear'):
        store_id = ' '.join(match.args()[1:])
        Data().clear_list(store_id)
        self.last_store_id = None
        return ['Success']

    if match.command('clear.all'):
        store_id = ' '.join(match.args()[1:])
        Data().clear_list(store_id, clear_all=True)
        return ['Success']


    if match.command('shop.at'):
        store_id = ' '.join(match.args()[1])
        items = Data().get_shopping_list_for_store(store_id)
        results = ['Shopping List']
        for item in items:
            results.append(str(item))
        return results

    if match.command('list'):
        items = Data().get_last_shopping_list()
        results = ['Shopping List']
        for item in items:
            results.append(str(item))
        return results

    if match.command('unsorted'):
        items = Data().get_unsorted_list()
        results = ['Items assigned to no store']
        for item in items:
            results.append(str(item))
        return results

    if match.command('remove.item'):
        item_id = ' '.join(match.args()[1:])
        Data().remove_item(item_id)
        return ['Success']

    if match.command('remove.store'):
        store_id = ' '.join(match.args()[1:])
        Data().remove_store(store_id)
        return ['Success']


    if match.command('extra.help'):
        return [extended_help]

    return [do_shop.__doc__]

async def shop_bot(room, message, bot):
    match = botlib.MessageMatch(room, message, bot, PREFIX)

    if not match.is_not_from_this_bot() and match.prefix():
        return

    try:
        if match.prefix():
            result_lines = await do_shop(match)
            for line in result_lines:
                await bot.api.send_text_message(
                    room.room_id, str(line))
    except Exception as ex:
        for line in ['You have:', '    no tea', str(ex)]:
            await bot.api.send_text_message(
                room.room_id, str(line))



