#include <zephyr/kernel.h>
#include <zephyr/net/net_if.h>
#include <zephyr/net/net_ip.h>

#include "led.h"
#include "tcp_server.h"

#define STATIC_IP_ADDR      "192.168.10.2"
#define STATIC_NETMASK      "255.255.255.0"

/* Function prototypes */
static int set_static_ipv4(struct net_if *iface);


int main(void)
{
    struct net_if *iface;
    int ret;

    printk("\nMy Nucleo F429ZI Direct Ethernet Test\n");

    /* Start LED heartbeat */
    led_init();

    /* Get default network interface */
    iface = net_if_get_default();

    if (iface == NULL) {
        printk("Network interface not found\n");
        return 0;
    }

    printk("Ethernet interface found\n");

    /* Configure static IPv4 address */
    ret = set_static_ipv4(iface);

    if (ret < 0) {
        printk("Static IPv4 configuration failed\n");
        return 0;
    }

    printk("Static IPv4 configuration complete\n");

    /* Start TCP server */
    tcp_server_start();    

    while (1) {
        k_sleep(K_SECONDS(1));
    }

    return 0;
}


static int set_static_ipv4(struct net_if *iface)
{
    struct in_addr ip_addr;
    struct in_addr netmask;

    if (net_addr_pton(AF_INET,
                      STATIC_IP_ADDR,
                      &ip_addr) < 0) {
        printk("Invalid IPv4 address\n");
        return -1;
    }

    if (net_addr_pton(AF_INET,
                      STATIC_NETMASK,
                      &netmask) < 0) {
        printk("Invalid netmask\n");
        return -1;
    }

    if (net_if_ipv4_addr_add(iface,
                             &ip_addr,
                             NET_ADDR_MANUAL,
                             0) == NULL) {
        printk("Failed to add IPv4 address\n");
        return -1;
    }

    if (!net_if_ipv4_set_netmask_by_addr(iface,
                                         &ip_addr,
                                         &netmask)) {
        printk("Failed to set netmask\n");
        return -1;
    }

    printk("IPv4 address: %s\n",
           STATIC_IP_ADDR);

    printk("Netmask: %s\n",
           STATIC_NETMASK);

    return 0;
}