/*
 * Example Wifi configuration via an access point.
 *
 * Copyright (C) 2016 OurAirQuality.org
 *
 * Licensed under the Apache License, Version 2.0, January 2004 (the
 * "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at
 *      http://www.apache.org/licenses/
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS WITH THE SOFTWARE.
 *
 */

#include <string.h>
#include <ctype.h>

#include <espressif/esp_common.h>
#include <espressif/user_interface.h>
#include <esp/uart.h>
#include <FreeRTOS.h>
#include <task.h>

#include "lwip/sockets.h"

#include "wificfg/wificfg.h"

#include "sysparam.h"

static const char http_success_header[] = "HTTP/1.0 200 \r\n"
    "Content-Type: text/html; charset=utf-8\r\n"
    "Cache-Control: no-store\r\n"
    "\r\n";
static const char *http_index_content[] = {
#include "content/index.html"
};

static void handle_index(int s, wificfg_method method,
                         uint32_t content_length,
                         wificfg_content_type content_type,
                         char *buf, size_t len)
{
    if (wificfg_write_string(s, http_success_header) < 0) return;

    if (method != HTTP_METHOD_HEAD) {
        if (wificfg_write_string(s, http_index_content[0]) < 0) return;

        socklen_t addr_len;
        struct sockaddr addr;
        addr_len = sizeof(addr);
        getpeername(s, (struct sockaddr*)&addr, &addr_len);

        if (wificfg_write_string(s, "<dl class=\"dlh\">") < 0) return;
        if (addr.sa_family == AF_INET) {
            struct sockaddr_in *sa = (struct sockaddr_in *)&addr;
            if (wificfg_write_string(s, "<dt>Peer address</dt>") < 0) return;
            snprintf(buf, len, "<dd>" IPSTR " : %d</dd>",
                     IP2STR(&sa->sin_addr), ntohs(sa->sin_port));
            if (wificfg_write_string(s, buf) < 0) return;
        }
        
        if (wificfg_write_string(s, "</dl>") < 0) return;
        if (wificfg_write_string(s, http_index_content[1]) < 0) return;
    }
}

static const wificfg_dispatch dispatch_list[] = {
    {"/", HTTP_METHOD_GET, handle_index, false},
    {"/index.html", HTTP_METHOD_GET, handle_index, false},
    {NULL, HTTP_METHOD_ANY, NULL}
};

void user_init(void)
{
    uart_set_baud(0, 115200);
    printf("SDK version:%s\n", sdk_system_get_sdk_version());

    sdk_wifi_set_sleep_type(WIFI_SLEEP_MODEM);

    wificfg_init(80, dispatch_list);
}