<gh_stars>0
# import libraries
from fastapi import APIRouter, Depends, status, BackgroundTasks, HTTPException, Request
from typing import Optional, List
from sqlalchemy.orm import Session
from decouple import config
import os
import json
from datetime import datetime
# include other functionality
from ..authentication import authenticate_user, authenticate_admin
from ..config.db import SessionLocal, get_db
from ..tools.logging import access_logging, error_logging
from ..database import crud, models, schemas
from ..tools import base64

# # # Values Definitions JSON # # # 
machine_root_directory = os.path.abspath(os.curdir)
parameter_file = open(f'{machine_root_directory}\\src\\parameters.json')
params = json.load(parameter_file)
parameter_file.close()
# Files format & encoding
ENCODING = str(params['encoding'])

# # # Find Date # # #
now = datetime.now() # current date and time
date_time = now.strftime("%Y-%m-%d_%H:%M:%S")

# Route base url
document_router = APIRouter(
    prefix=f"{config('API_URL')}/documents",
    tags=['Documents']
)


# Read all method
@document_router.get("/", response_model=List[schemas.Document], status_code = status.HTTP_200_OK)
async def read_documents(request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    documents = await crud.get_documents(db, skip=skip, limit=limit)
    background_tasks.add_task(access_logging, str(request.url), 'Read all documents', username, "200", str(dict(request.headers)))
    return documents


# Read one method by id
@document_router.get("/{document_id}", response_model=schemas.Document, status_code = status.HTTP_200_OK)
async def read_document_by_id(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document', username, "200", str(dict(request.headers)))
        return db_document
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Read one method by name
@document_router.get("/name/{name}", response_model=schemas.Document, status_code = status.HTTP_200_OK)
async def read_document_by_name(name: str, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document_by_name(db, name=name)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document', username, "200", str(dict(request.headers)))
        return db_document
    background_tasks.add_task(error_logging, str(request.url), 'Document name not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document name not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Get one method content
@document_router.get("/{document_id}/content", status_code = status.HTTP_200_OK)
async def read_document_content(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document content', username, "200", str(dict(request.headers)))
        return {"name": db_document.name, "content": db_document.content}
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Read one method by id get base64 format
@document_router.get("/{document_id}/encoding", status_code = status.HTTP_200_OK)
async def receive_document_encoded_by_id(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
    # add the encoding file
        base64_document = await base64.document_convert_to_base64(ENCODING, document_fullname)
        if base64_document is None:
            background_tasks.add_task(error_logging, str(request.url), 'Document is blank', username, "204", str(dict(request.headers)))
            raise HTTPException(
                status_code=204, 
                detail="Document is blank",
                headers={"WWW-Authenticate": "Basic"},
                )
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document in base64 format', username, "200", str(dict(request.headers)))
        return {"encoding": base64_document}
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Delete one method
@document_router.delete("/{document_id}", status_code = status.HTTP_202_ACCEPTED)
async def delete_document(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        if os.path.exists(document_fullname):
            os.remove(document_fullname)
            background_tasks.add_task(access_logging, str(request.url), 'Delete specific document', username, "202", str(dict(request.headers)))
            return await crud.delete_document(db, document_id=document_id)
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
            status_code=404, 
            detail="Document not found",
            headers={"WWW-Authenticate": "Basic"},
            )

# import libraries
from fastapi import APIRouter, Depends, status, BackgroundTasks, HTTPException, Request
from typing import Optional, List
from sqlalchemy.orm import Session
from decouple import config
import os
import json
from datetime import datetime
# include other functionality
from ..authentication import authenticate_user, authenticate_admin
from ..config.db import SessionLocal, get_db
from ..tools.logging import access_logging, error_logging
from ..database import crud, models, schemas
from ..tools import base64

# # # Values Definitions JSON # # # 
machine_root_directory = os.path.abspath(os.curdir)
parameter_file = open(f'{machine_root_directory}\\src\\parameters.json')
params = json.load(parameter_file)
parameter_file.close()
# Files format & encoding
ENCODING = str(params['encoding'])

# # # Find Date # # #
now = datetime.now() # current date and time
date_time = now.strftime("%Y-%m-%d_%H:%M:%S")

# Route base url
document_router = APIRouter(
    prefix=f"{config('API_URL')}/documents",
    tags=['Documents']
)


# Read all method
@document_router.get("/", response_model=List[schemas.Document], status_code = status.HTTP_200_OK)
async def read_documents(request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    documents = await crud.get_documents(db, skip=skip, limit=limit)
    background_tasks.add_task(access_logging, str(request.url), 'Read all documents', username, "200", str(dict(request.headers)))
    return documents


# Read one method by id
@document_router.get("/{document_id}", response_model=schemas.Document, status_code = status.HTTP_200_OK)
async def read_document_by_id(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document', username, "200", str(dict(request.headers)))
        return db_document
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Read one method by name
@document_router.get("/name/{name}", response_model=schemas.Document, status_code = status.HTTP_200_OK)
async def read_document_by_name(name: str, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document_by_name(db, name=name)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document', username, "200", str(dict(request.headers)))
        return db_document
    background_tasks.add_task(error_logging, str(request.url), 'Document name not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document name not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Get one method content
@document_router.get("/{document_id}/content", status_code = status.HTTP_200_OK)
async def read_document_content(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document content', username, "200", str(dict(request.headers)))
        return {"name": db_document.name, "content": db_document.content}
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Read one method by id get base64 format
@document_router.get("/{document_id}/encoding", status_code = status.HTTP_200_OK)
async def receive_document_encoded_by_id(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
    # add the encoding file
        base64_document = await base64.document_convert_to_base64(ENCODING, document_fullname)
        if base64_document is None:
            background_tasks.add_task(error_logging, str(request.url), 'Document is blank', username, "204", str(dict(request.headers)))
            raise HTTPException(
                status_code=204, 
                detail="Document is blank",
                headers={"WWW-Authenticate": "Basic"},
                )
        background_tasks.add_task(access_logging, str(request.url), 'Read specific document in base64 format', username, "200", str(dict(request.headers)))
        return {"encoding": base64_document}
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
        status_code=404, 
        detail="Document not found",
        headers={"WWW-Authenticate": "Basic"},
        )


# Delete one method
@document_router.delete("/{document_id}", status_code = status.HTTP_202_ACCEPTED)
async def delete_document(document_id: int, request: Request, background_tasks: BackgroundTasks, username: str = Depends(authenticate_user), db: Session = Depends(get_db)):
    db_document = await crud.get_document(db, document_id=document_id)
    document_fullname = machine_root_directory + db_document.file_path + db_document.file_name
    if db_document and os.path.exists(document_fullname):
        if os.path.exists(document_fullname):
            os.remove(document_fullname)
            background_tasks.add_task(access_logging, str(request.url), 'Delete specific document', username, "202", str(dict(request.headers)))
            return await crud.delete_document(db, document_id=document_id)
    background_tasks.add_task(error_logging, str(request.url), 'Document not found', username, "404", str(dict(request.headers)))
    raise HTTPException(
            status_code=404, 
            detail="Document not found",
            headers={"WWW-Authenticate": "Basic"},
            )
# import libraries # include other functionality # # # Values Definitions JSON # # # # Files format & encoding # # # Find Date # # # # current date and time # Route base url # Read all method # Read one method by id # Read one method by name # Get one method content # Read one method by id get base64 format # add the encoding file # Delete one method