import re
from fastapi import APIRouter
from bson.objectid import ObjectId
from server.mock.schemas import Table
from server.mock.model import Table_helper
from server.service.database import get_connection

table = APIRouter()
collection = get_connection('table')

@table.get('/table/{sid}')
async def get_table(sid:str):
    return [Table_helper(i) for i in collection.find({'shop_id': sid})]

@table.get('/table/{sid}/{id}')
async def get_table_by_id(sid: str, id: str):
    table = collection.find_one({'shop_id': sid, '_id': ObjectId(id)})
    return Table_helper(table)

@table.post('/table')
async def create_table(table: Table):
    payload = {
        'shop_id' : table.shop_id,
        'session_key' : table.session_key,
        'name' : table.name,
        'sit_number' : table.sit_number,
        'status' : table.status
    }
    collection.insert_one(payload)
    return [Table_helper(i) for i in collection.find({'shop_id': table.shop_id})]

@table.patch('/table_data/{sid}/{id}')
async def update_table_data(sid: str, id: str, table: Table):
    payload = {
        'name': table.name,
        'sit_number': table.sit_number
    }
    collection.update_one({"_id": ObjectId(id)}, {"$set": payload})
    return [Table_helper(i) for i in collection.find({'shop_id': sid})]

@table.patch('/table_status/{sid}/{id}')
async def update_table_status(sid: str, id: str, table: Table):
    payload = {
        'session_key': table.session_key,
        'status': table.status,
    }
    collection.update_one({"_id": ObjectId(id)}, {"$set": payload})
    return [Table_helper(i) for i in collection.find({'shop_id': sid})]

@table.delete("/table/{sid}/{id}")
async def delete_table(sid: str, id: str):
    collection.delete_one({"_id": ObjectId(id)})
    return [Table_helper(i) for i in collection.find({'shop_id': sid})]

# @table.get("/verify_table/{key}")
# async def verify_table(key: str):
#     table = collection.find_one({"session_key": key})
#     if table is None:
#         return {"status": "Table session have no longer"}
#     else:
#         return {"status": True}