/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


#include <eCxx/eCxx_Server.h>

#include "NodeMCU_Common.h"


//
// The web server
//
static eCxx::WebServer webServer(80);


//
// The init function
//
void eCxx_user_init()
{
    // Initialize application
    initBasicNodeMCUApp();

    // There is no need to enable the 74LVC541 buffers on the eCxx NodeMCU development board because
    // the UART is only used for communication with the host PC

    // Initialize UART
    App::uart().begin(9600);

    // Create the static file to be served if it does not exist yet
    constexpr char staticFileName[] = "/test.html";

    if( App::nvFileExists(staticFileName) ) {
        App::uart().writeStringln( PGM_STR("\nFound file '/test.html'") );
    }
    else {
        App::uart().writeStringln( PGM_STR("\nCreating '/test.html' ...") );
        auto f = App::nvOpenFileForWriting(staticFileName);
        if(!f) {
            App::uart().writeStringln( PGM_STR("Cannot create '/test.html'; application halted!") );
            App::halt();
        }
        f.write("<b>This is a statically served file!</b>");
        f.flush();
        f.close();
    }

    // Intialize web server
    webServer.onNotFound( []() {
        // Send response
        webServer.send(404, "text/plain", "Not found");
        // Write to UART
        App::uart().writeStringln( PGM_STR("\nwebServer.onNotFound()") );
        App::uart().writeStringln( webServer.uri()                     );
    } );

    webServer.on( "/", []() {
        // Send response
        webServer.send(200, "text/plain", "OK");
        // Write to UART
        App::uart().writeStringln( PGM_STR("\nwebServer.on(\"/\")") );
    } );

    webServer.on( "/console/baud", []() {
        // Send response
        webServer.send(200, "text/plain", "OK");
        // Write to UART (example request: http://192.168.0.100/console/baud?rate=115200&format=8N1)
        App::uart().writeStringln( PGM_STR("\nwebServer.on(\"console/baud\")") );
        for(eCxx::uint8_t i = 0; i < webServer.argCount(); i++) {
            App::uart().writeString  ( webServer.argName (i) );
            App::uart().writeString  ( PGM_STR(" : ")        );
            App::uart().writeStringln( webServer.argValue(i) );
        }
    } );

    webServer.serveStaticFileFromInternalFlash("/static", staticFileName);

    webServer.begin();
}


//
// The task function
//
void eCxx_user_task()
{
    // Process event
    eCxx::Application::processEvent();

    // Handle the web server client
    webServer.handleClient();
}
