// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-or-later

/**
 * @file 03.Multipart.ino
 * @brief Parse a multipart/form-data POST body (RFC 7578) in place.
 *
 * POST /upload with a multipart body; multipart_parse() splits it into parts and
 * multipart_get_field() returns a named text field. The whole body must fit in
 * BODY_BUF_SIZE (no streaming), so this suits small form fields / tiny uploads.
 * A test form is served at /.
 *
 * Flash, open Serial @ 115200 for the IP, then browse to http://<ip>/.
 */

#include "dwserver.h"
#include "network_drivers/physical/physical.h"
#include <WiFi.h>

static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";

DetWebServer server;

static const char FORM[] = "<!doctype html><meta charset=utf-8><title>upload</title>"
                           "<form method=POST action=/upload enctype=multipart/form-data>"
                           "<input name=name placeholder=name> "
                           "<input type=file name=file> <button>upload</button></form>";

void handle_upload(uint8_t id, HttpReq *req)
{
    Multipart mp;
    if (!multipart_parse(req, &mp))
    {
        server.send(id, 400, "text/plain", "expected multipart/form-data (and within BODY_BUF_SIZE)");
        return;
    }
    const char *name = multipart_get_field(&mp, "name");
    char out[160];
    snprintf(out, sizeof(out), "parsed %d part(s); field 'name' = %s", mp.part_count, name ? name : "(absent)");
    server.send(id, 200, "text/plain", out);
}

void setup()
{
    Serial.begin(115200);
    init_wifi_physical(SSID, PASSWORD);
    Serial.print("Connecting to WiFi");
    while (!wifi_ready())
    {
        delay(250);
        Serial.print('.');
    }
    Serial.print("\nIP: ");
    Serial.println(WiFi.localIP());
    WiFi.setSleep(false);

    server.on("/", HTTP_GET, [](uint8_t id, HttpReq *) { server.send(id, 200, "text/html", FORM); });
    server.on("/upload", HTTP_POST, handle_upload);
    server.begin(80);
}

void loop()
{
    server.handle();
}
