from fastapi import APIRouter, Body, Cookie, Depends
from sqlalchemy.orm import Session
from typing import List
import json

from db import schemas, crud
from db.database import get_db
from routers.websocket import manager


router = APIRouter(prefix="/api", tags=["comments"])


@router.get('/{place}/comments', response_model=List[schemas.Comment])
async def get_comments(place: str, page: int = 1, db: Session = Depends(get_db)):
    return crud.get_comments(place, page, db)


@router.post('/{place}/comments', response_model=schemas.Comment)
async def create_comment(place: str, connect_id: str = Cookie(...), comment: schemas.CommentBase = Body(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    if user:
        saved_comment = crud.create_comment(user, place, comment, db)
        await manager.broadcast(json.dumps({"type": "comment", "comment": saved_comment.dict()}, default=str))
        return saved_comment
    else:
        raise Exception


@router.delete('/comments/{id}', response_model=None)
async def delete_comment(id: int, db: Session = Depends(get_db)):
    return crud.delete_comment(id, db)
