#include <string>
#include <iostream>
#include <stdlib.h>
#include "httplib.h"
#include "http.h"

using namespace std;

int start_http_server(int port, http_handle_file handle_file)
{
    httplib::Server svr;

    svr.Post("/roi", [handle_file](const httplib::Request &req, httplib::Response &res) {
        auto f = req.get_file_value("file");
        vector<uint8_t> input(f.content.begin(), f.content.end());
        vector<uint8_t> output;
        if (!input.size()) {
            res.status = 400;
            res.set_content("file is missing\n", "text/plain");
        } else {
            int r = handle_file(input, output);
            if (r) {
                res.status = 400;
                res.set_content("failed to process file\n", "text/plain");
            } else {
                res.status = 200;
                res.set_content((char *)&output[0], output.size(), "image/jpeg");
            }
        }
     });

    cout << "starting server on port " << port << endl;
    svr.listen("0.0.0.0", port);

    return 0;
}
