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

repo = Repository()

def post():
    body = request.json
    _insert_layer(body)
    return Response(status=201)

def _insert_layer(layer_data: dict):
    # convert object keys from ext source
    layer_data['layer_name'] = layer_data.pop('LayerName')
    layer_data['nodes'] = layer_data.pop('Nodes')
    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_names():
    return repo.get_layer_names()

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)