from flask import request, Response
from db.repository import Repository
from db.entities import Layer

repo = Repository()

#region layers
def post():
    '''Insert a new layer or overwrite an existing one.'''
    # TODO overwrite
    body = request.json
    _insert_layer(body)
    return Response(status=201)

def _insert_layer(layer_data: dict):
    '''Converts object keys from external source and inserts into database.'''
    layer_data['layer_name'] = layer_data.pop('LayerName')
    layer_data['properties'] = layer_data.pop('Properties')

    repo.add_layer(Layer(layer_data))

def get():
    return [l.to_serializable_dict() for l in repo.get_layers()]

def get_by_name(name):
    res = repo.get_layer(name)
    if res is not None:
        return res.to_serializable_dict() 
    else:
        return Response(status=404)

#endregion

#region nodes
def get_nodes(name):
    res = repo.get_layer_nodes(name)
    # print(res)
    return res

def post_nodes(name):
    body = request.json
    for node in body:
        node['layer_name'] = name

    repo.add_layer_nodes(body)
    return Response(status=201)

#endregion nodes