package de.thpeetz.kontor.web;

import java.util.LinkedList;
import java.util.List;

import de.thpeetz.kontor.infrastructure.AppHibernate;
import io.javalin.http.Handler;
import io.javalin.http.HttpStatus;
import de.thpeetz.kontor.models.media.MediaFile;
import de.thpeetz.kontor.web.model.NewMediaFile;
import de.thpeetz.kontor.web.model.ResultMediaFile;

public class MediaFileHandler {

    public static Handler listAll = (context) -> {
        List<MediaFile> result = new LinkedList<>();
        context.json(new ResultMediaFile(result));
    };

    public static Handler save = (context) -> {
        var newMediaFile = context.bodyAsClass(NewMediaFile.class);
        var result = AppHibernate.fromTransaction(session -> {
            var insertedId = session.insert(MediaFile.newMediaFile(newMediaFile.url()));
            return session.get(MediaFile.class, insertedId);
        });
        context.json(result).status(HttpStatus.CREATED);
    };

}
