from datetime import datetime as dt
import logging
import os

import simplematrixbotlib as botlib

from .db import Data as ChoreData


SERVER = os.environ.get('MATRIX_SERVER')
BOT_NAME = os.environ.get('MATRIX_BOT')
BOT_PWD = os.environ.get('MATRIX_BOT_PWD')
DATA_DIR = os.environ.get('MATRIX_DATA_DIR')

CHORES = ChoreData(os.path.join(DATA_DIR}, 'chores.db'))

def get_bot():
    creds = botlib.Creds(SERVER, BOT_NAME, BOT_PWD)
    return botlib.Bot(creds)

logger = logging.getLogger(__name__)
logging.basicConfig(filename='matrix-chore-bot.log', encoding='utf-8', level=logging.DEBUG)
logging.getLogger('nio').setLevel(logging.WARNING)

async def chore_bot(room, message, bot):
    match = botlib.MessageMatch(room, message, bot, '!chore')

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

    if match.prefix():
        try:
            result_lines = await handle_chore(match)
            for line in result_lines:
                await bot.api.send_text_message(
                    room.room_id, str(line))
        except Exception as ex:
            line = 'Ye flask must be load bearing, or something...'
            await bot.api.send_text_message(
                room.room_id, str(line))


async def handle_chore(match):
    '''
    Prefix: !chore

    Synax:
        !chore COMMAND ARGS

    Commands:
      help - show this help
      add - add a chore 
      check - check status of a chore
      done - mark a chore as done
      list - print the chore list
      undo - mark a chore as undone
    '''

    if match.command('list'):
        results = ['## Listing chores...']
        for item in CHORES.list():
            results.append(item)
        results.append('-- End of List --')
        return results
    
    if match.command('setup'):
        results = []
        results.append('Doing chore setup...')
        result = CHORES.setup()
        results.append(str(result))
        return results

    if match.command('add'):
        new_chore = ' '.join(match.args()[1:])
        result = CHORES.add(new_chore)
        return [result]

    if match.command('check'):
        chore_id = match.args()[1]
        result = CHORES.check(chore_id)
        return [result]

    if match.command('done'):
        chore_id = match.args()[1]
        result = CHORES.done(chore_id)
        return [result]

    if match.command('undo'):
        chore_id = match.args()[1]
        result = CHORES.undo(chore_id)
        return [result]

    if match.command('remove'):
        chore_id = match.args()[1]
        result = CHORES.remove(chore_id)
        return [result]

    return [handle_chore.__doc__]

