#include "comm.h"


void CommunicationsController::initOta() {
    ArduinoOTA.setHostname(WIFI_SSID);
    ArduinoOTA.setPassword(WIFI_PASSWORD);
    ArduinoOTA.begin();
}

void CommunicationsController::initWifi() {
    WiFiSettings.hostname = WIFI_SSID;
    WiFiSettings.password = WIFI_PASSWORD;

    WiFiSettings.onPortalWaitLoop = []() {
        ArduinoOTA.handle();
    };

    WiFiSettings.connect();
}

void CommunicationsController::init() {
    initOta();
    initWifi();
    WebMonitor.begin();
}

void CommunicationsController::process() {
    ArduinoOTA.handle();

    if (!l4s) {
        return;
    }

    if (l4s.connected()) {

        handle_client();
    } else {
        create_connection();
    }
}

void CommunicationsController::handle_client() {
    l4s.flush();
    received = recv();
    WebMonitor.println(received);
}

void CommunicationsController::parseLook4Sat(float* azimuth, float* altitude) {
    *azimuth  = received.substring(0, 3).toFloat();
    *altitude = received.substring(3, 6).toFloat(); //TODO
}

void CommunicationsController::create_connection() {
    l4s = l4sServer.accept();
}

String CommunicationsController::recv() {
    String rec = "";

    while (l4s.available()) {
        rec += (char)(l4s.read());
    }

    if (rec.length() == 0) {
        rec = "Ç";
    }
    return rec;
}
