'''
Prefix: !fridge

Synax:
!fridge COMMAND ARGS

Commands:
add - add an item
list - print the list of fresh items
remove - remove an item
to.toss - print the list of items to toss
filter TERM - list all items that include TERM
'''

from datetime import datetime as dt
import logging
import os

import simplematrixbotlib as botlib

from .db import Data 

logger = logging.getLogger(__name__)
logging.getLogger('nio').setLevel(logging.WARNING)

MODULE='fridge'

class FridgeBot():
    def __init__(self, matrix_server,
                 bot_name,
                 bot_pwd,
                 db_file=None,
                 bot_prefix='.fridge'):

        logging.basicConfig(filename=f'matrix-{MODULE}-bot.log', encoding='utf-8', level=logging.DEBUG)


        creds = botlib.Creds(matrix_server, bot_name, bot_pwd)
        self.bot = botlib.Bot(creds)
        self.prefix = bot_prefix
        self.data = Data(db_file=db_file)

    def run(self):
        self.bot.run()

    async def handle_message(self, room, message):
        match = botlib.MessageMatch(room, message, self.bot, self.prefix)

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

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


    async def _handle_match(self, match):

        if match.command('list'):
            results = ['## Listing fresh items...']
            for item in self.data.list():
                results.append(item)
            results.append('-- End of List --')
            return results


        if match.command('toss'):
            results = ['## Listing items to toss...']
            for item in self.data.to_toss():
                results.append(item)
            results.append('-- End of List --')
            return results


        if match.command('filter'):
            term = ' '.join(match.args()[1:])
            results = [f'## List matching {term}']
            for item in self.data.filter(term):
                results.append(item)
            results.append('-- End of List --')
            return results
        
        if match.command('setup'):
            results = []
            results.append('Doing fridge setup...')
            result = self.data.setup()
            results.append(str(result))
            return results

        if match.command('add'):
            new_fridge = ' '.join(match.args()[1:])
            result = self.data.add(new_fridge)
            return [result]


        if match.command('remove'):
            fridge_id = match.args()[1]
            result = self.data.remove(fridge_id)
            return [result]

        return [__doc__]

