#global imports
from db.table_repository import TableRepository
from db.use_case_repository import UseCaseRepository
from db.entities.table import Table

from flask import Response, request

table_repository = TableRepository()
use_case_repository = UseCaseRepository()

def all():
    return [t.to_serializable_dict() for t in table_repository.get_all()]

def all_for_use_case(use_case:str):
    return [t.to_serializable_dict() for t in table_repository.get_all_for_use_case(use_case)]

def put_mapping(use_case:str, name:str):
    body = request.json

    if "internal" not in body or "external" not in body:
        return Response(status=400, response=f"Field missing! Fields required: (internal, external)")
    
    table = table_repository.get_for_use_case_and_name(use_case, name)

    if table == None:
        print("table not there, creating it...")
        table = table_repository.add(Table(use_case, name, {}))
    
    table.add_mapping(body["internal"], body["external"])
    table_repository.update(table)

    return Response(status=200)

def add_complete(use_case: str):
    body = request.json
    body["use_case"] = use_case

    # check if fields are present
    if "name" not in body or "mappings" not in body:
        return Response(status=400, response="Field missing! Fields required: (name, mappings)")

    # check if table exists
    table_reference = table_repository.get_for_use_case_and_name(body["use_case"], body["name"])
    if table_reference != None:
        return Response(status=400, response="Table already exists!")
    
    use_case_repository.put(body["use_case"])

    table_new = Table.from_serializable_dict(body)
    table_repository.add(table_new)

    return Response(status=200)

def delete_all_for_use_case(use_case: str):
    table_repository.delete_for_use_case(use_case)
    return Response(status=200)

def delete_all():
    table_repository.delete_all()
    return Response(status=200)