/*
 * 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);

    // 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( "/", []() {
        // Authenticate
        if( !webServer.authenticate("username", "password") ) {
            return webServer.requestAuthentication(
                eCxx::HTTPAuthMethod::Digest,
                "Enter Username and Password",
                "Invalid username and/or password!"
            );
        }
        // Send response
        webServer.send(200, "text/plain", "OK");
        // Write to UART
        App::uart().writeStringln( PGM_STR("\nwebServer.on(\"/\")") );
    } );

    webServer.begin();
}


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

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