from microdot import Microdot
from models.pallet import Palette
import json

controller = Microdot()
palettes = Palette()

@controller.get('')
async def list_palettes(request):
    """List all palettes."""
    return json.dumps(palettes), 200, {'Content-Type': 'application/json'}

@controller.get('/<id>')
async def get_palette(request, id):
    """Get a specific palette by ID."""
    palette = palettes.read(id)
    if palette:
        return json.dumps(palette), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Palette not found"}), 404

@controller.post('')
async def create_palette(request):
    """Create a new palette."""
    try:
        data = request.json or {}
        name = data.get("name", "")
        colors = data.get("colors", None)
        palette_id = palettes.create(name, colors)
        if data:
            palettes.update(palette_id, data)
        return json.dumps(palettes.read(palette_id)), 201, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.put('/<id>')
async def update_palette(request, id):
    """Update an existing palette."""
    try:
        data = request.json
        if palettes.update(id, data):
            return json.dumps(palettes.read(id)), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Palette not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.delete('/<id>')
async def delete_palette(request, id):
    """Delete a palette."""
    if palettes.delete(id):
        return json.dumps({"message": "Palette deleted successfully"}), 200
    return json.dumps({"error": "Palette not found"}), 404
