from fastapi import APIRouter, HTTPException, Response, Cookie, Depends
from sqlalchemy.orm import Session
from typing import List

from db import schemas, crud
from db.database import get_db


router = APIRouter(prefix="/api")


@router.get('/records', response_model=List[schemas.Record], tags=["records"])
async def get_records(place: str, db: Session = Depends(get_db)):
    return crud.get_records(place, db)


@router.post('/records', response_model=schemas.Record, tags=["records"])
async def stats(record: schemas.RecordBase, db: Session = Depends(get_db)):
    return crud.create_record(record, db)


@router.delete('/records', response_model=None, tags=["records"])
async def stats(id: int, db: Session = Depends(get_db)):
    return crud.delete_record(id, db)


@router.get('/collection', response_model=List[schemas.CollaborativeRecords], tags=["data collection"])
async def get_collection_records(place: str, db: Session = Depends(get_db)):
    return crud.get_collaborative_records(place, db)


@router.post("/collection/start/{place}", response_model=schemas.CollaborativeRecords, tags=["data collection"])
async def create_new_record(response: Response, place: str, connect_id: str = Cookie(default=None), db: Session = Depends(get_db)):
    if connect_id:
        try:
            user = crud.get_user(connect_id, db)
        except HTTPException:
            response.delete_cookie("connect_id")
            user = crud.init_user(db)
    else:
        user = crud.init_user(db)
    db_record = crud.create_collaborative_record(user, place, db)
    response.set_cookie(key="connect_id", value=user.cookie)
    return schemas.CollaborativeRecords(**db_record.__dict__)


@router.post("/collection/stop", response_model=schemas.CollaborativeRecords, tags=["data collection"])
async def end_new_record(response: Response, connect_id: str = Cookie(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    db_record = crud.update_collaborative_record(user, db)
    if not user.username:
        crud.delete_user(user.cookie, db)
        response.delete_cookie(key="connect_id")
    return db_record


@router.post("/collection/cancel", response_model=None, tags=["data collection"])
async def cancel_new_record(response: Response, connect_id: str = Cookie(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    db_record = crud.cancel_collaborative_record(user.id, db)
    if not user.username:
        crud.delete_user(user.cookie, db)
        response.delete_cookie(key="connect_id")
    return db_record


@router.delete('/collection', response_model=None, tags=["data collection"])
async def delete_record(id: int, db: Session = Depends(get_db)):
    return crud.delete_collaborative_record(id, db)
