#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();

    while (WiFi.status() != WL_CONNECTED);

    WebMonitor.begin();
    l4sServer.begin();
}

byte CommunicationsController::process(float *azimuth, float *altitude) {
    ArduinoOTA.handle();
    
    l4s = l4sServer.accept();

    if (l4s) {
        while (l4s.connected()) {
            ArduinoOTA.handle();
            
            l4s.flush();
            received = recv();

            byte resp = parseLook4Sat(azimuth, altitude);

            if (resp == 1) {
                return 1;
            }
        }
    }

    return 0;
}

byte CommunicationsController::parseLook4Sat(float* azimuth, float* altitude) {
    String tmp = received.substring(9);
    int spaceIndex = tmp.indexOf(' ');

    if (spaceIndex != -1) {
        *azimuth = tmp.substring(0, spaceIndex).toFloat();
        *altitude = tmp.substring(spaceIndex+1).toFloat();

        return 1;
    }

    return 0;
}

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

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

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