/*
 * 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::WebServerSSL webServer(443);


//
// The certificate and private key
//
// openssl req -x509 -newkey rsa:1024 -sha256 -keyout private_key.txt -out certificate.txt -days 18263 -nodes -subj "/C=XX/ST=OpenSource/L=Internal/O=eCxx/OU=NodeMCU/CN=esp8266.local"

static const char PROGMEM certificate[] = R"EOF(
-----BEGIN CERTIFICATE-----
MIICrDCCAhWgAwIBAgIJAJFwPuwrEWSDMA0GCSqGSIb3DQEBCwUAMG4xCzAJBgNV
BAYTAlhYMRMwEQYDVQQIDApPcGVuU291cmNlMREwDwYDVQQHDAhJbnRlcm5hbDEN
MAsGA1UECgwEZUN4eDEQMA4GA1UECwwHTm9kZU1DVTEWMBQGA1UEAwwNZXNwODI2
Ni5sb2NhbDAgFw0yMDA3MDEwMDQ0MDFaGA8yMDcwMDcwMjAwNDQwMVowbjELMAkG
A1UEBhMCWFgxEzARBgNVBAgMCk9wZW5Tb3VyY2UxETAPBgNVBAcMCEludGVybmFs
MQ0wCwYDVQQKDARlQ3h4MRAwDgYDVQQLDAdOb2RlTUNVMRYwFAYDVQQDDA1lc3A4
MjY2LmxvY2FsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDaT5SxrFTI8RLA
7jTcq3LrPaIooqbrV50hnQWI9+EQyBOLj6tr9j6tCR88NThf/WW3pICm8n+UVdHb
6Ge3gMY5+3RrZhsBae1KbV9+acLvJwviIJbeyVqwlemp2yIBuIlIAj6qOWrkUo2C
ae0OJhFVQyov4YQFUQQn1/Hg3YwGHQIDAQABo1AwTjAdBgNVHQ4EFgQUA5MPIJms
SS+KPV7Kg1R+AAfaAYkwHwYDVR0jBBgwFoAUA5MPIJmsSS+KPV7Kg1R+AAfaAYkw
DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQ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Iv9DG1J1
0JrZDyKGJb8LA9aI
-----END PRIVATE KEY-----
)EOF";


//
// 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.setRSACertificate( eCxx::PGM_PTR(certificate), eCxx::PGM_PTR(privateKey) );

    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.begin();
}


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

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