import asyncio, aiosqlite, datetime


class DataBase:
    def __init__(self, file):
        self.file = file

    async def get_position_info(self, index, value, menu_id=1):
        async with aiosqlite.connect(self.file) as db:
            cursor = await db.execute(f'SELECT {value} FROM position WHERE position = {index} AND menu_id = {menu_id}')
            
            data = await cursor.fetchone()
            await cursor.close()

            if data == None:
                return 0
            elif data:
                return data[0]
            
    async def update_position(self, index, key, value, menu_id=1):
        async with aiosqlite.connect(self.file) as db:
            if isinstance(value, str):
                cursor = await db.execute(f'UPDATE position SET {key} = "{value}" WHERE position={index} AND menu_id={menu_id}')

            else:
                cursor = await db.execute(f'UPDATE position SET {key} = {value} WHERE position={index} AND menu_id={menu_id}')

            await db.commit()
            await cursor.close()

    async def update_column(self, key, value, menu_id=1):
        async with aiosqlite.connect(self.file) as db:
            if isinstance(value, str):
                cursor = await db.execute(f'UPDATE position SET {key} = "{value}" WHERE menu_id = {menu_id}')

            else:
                cursor = await db.execute(f'UPDATE position SET {key} = {value} WHERE menu_id = {menu_id}')

            await db.commit()
            await cursor.close()

    async def clear_position(self, key, index, menu_id=1):
        async with aiosqlite.connect(self.file) as db:
            cursor = await db.execute(f'UPDATE position SET {key} = NULL WHERE position={index} AND menu_id={menu_id}')

            await db.commit()
            await cursor.close()
    
    async def get_menu_list(self):
        """Возвращает список доступных меню"""
        async with aiosqlite.connect(self.file) as db:
            cursor = await db.execute('SELECT DISTINCT menu_id FROM position ORDER BY menu_id')
            menus = await cursor.fetchall()
            await cursor.close()
            return [menu[0] for menu in menus]
    