#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "command/command.h"
#include "wm_include.h"
#include "FreeRTOS.h"
#include "task.h"
#include "lwip/netif.h"

extern int shell_printf(const char *format, ...);
extern int wm_printf(const char *fmt,...);

extern int demo_bt_enable();
extern int demo_bt_destroy();
extern int demo_ble_server_on();
extern int demo_ble_server_off();

void tls_wifi_client_event_cb(u8 *mac, enum tls_wifi_client_event_type event)
{
  struct tls_sta_info_t *mac_addr = (struct tls_sta_info_t *)mac;

  shell_printf("Client event(%d), MAC : %M\n", event, mac_addr);
}

void wifi_scan_result_cb(void)
{
  u16 buffer_size = sizeof(struct tls_scan_bss_t) + sizeof(struct tls_bss_info_t) * 20;
  u8 *buf = tls_mem_alloc(buffer_size);
  if(buf == NULL)
  {
    shell_printf("Failed to allocate result buffer\n");
    return;
  }
  struct tls_scan_bss_t *scan_result = (struct tls_scan_bss_t *)buf;
  struct tls_bss_info_t *station_list = scan_result->bss;

  tls_wifi_get_scan_rslt(buf, buffer_size);
  shell_printf("Found %u nearby station(s) - info size(%u/%u)\n",
  scan_result->count,
  scan_result->length,
  buffer_size);

  for(u8 i = 0; i < scan_result->count; i++)
  {
    station_list[i].ssid[station_list[i].ssid_len] = '\0';
    shell_printf("station %u :\nSSID : %s\nBSSID : %02X:%02X:%02X:%02X:%02X:%02X\nRSSI : %d dB\nChannel : %u\nMax DR : %u Mbps\nMode %u\nAuth :%u\nWPS supported : %u\n\n",
    i,
    (char *)station_list[i].ssid,
    station_list[i].bssid[0], station_list[i].bssid[1], station_list[i].bssid[2], station_list[i].bssid[3], station_list[i].bssid[4], station_list[i].bssid[5],
    (s8)station_list[i].rssi,
    station_list[i].channel,
    station_list[i].max_data_rate,
    station_list[i].mode,
    station_list[i].privacy,
    station_list[i].wps_support);
  }

  tls_mem_free(buf);
}

void tls_wifi_data_ext_recv_cb(u8* data, u32 data_len, struct tls_wifi_ext_t *ext)
{
  shell_printf("recv packet :\nrssi : %d\nrate : %u\n", (s8)ext->rssi, ext->rx_rate);
  for(u32 i = 0; i < data_len; i++)
  {
    shell_printf("%02X", data[i]);
    if(i % 30 == 0)
      shell_printf("\n");
  }
  shell_printf("\n");
}

void tls_rtc_irq_cb(void *arg)
{
  struct tm rtc_time;
  tls_get_rtc(&rtc_time);

  shell_printf("rtc isr called\ntime is :\n%d:%d:%d %d/%d/%d\n",
  rtc_time.tm_hour,
  rtc_time.tm_min,
  rtc_time.tm_sec,
  rtc_time.tm_mday,
  rtc_time.tm_mon,
  rtc_time.tm_year);

  tls_rtc_timer_stop();
}

int _system(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "list_task") == 0)
    {
      char *buf = NULL;

      buf = tls_mem_alloc(1024);
      if(NULL == buf)
        return 0;
#if configUSE_TRACE_FACILITY
      vTaskList(buf);
#endif
      shell_printf("\n%s\nbuf_len : %d\n", buf, strlen(buf));
      tls_mem_free(buf);
      buf = NULL;
    }
    else if(strcmp(argv[1], "ram_usage") == 0)
    {
      shell_printf("Free heap : %u byte(s)\n", xPortGetFreeHeapSize());
    }
    else
    {
      shell_printf("Unknown %s action\n", argv[0]);
    }
  }
  else
  {
    shell_printf("List of system actions :\nlist_task\nram_usage\n");
  }
  return 0;
}

int _reset(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  tls_sys_reset();
  return 0;
}

int _soft_ap(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "state") == 0)
    {
      shell_printf("SOFT AP state : %u\n", tls_wifi_softap_get_state());
    }
    else if(strcmp(argv[1], "create") == 0)
    {
      struct tls_softap_info_t ap_info;
      struct tls_ip_info_t ip_info;

      tls_wifi_set_oneshot_flag(0);
      tls_wifi_softap_destroy();

      shell_printf("Registering client event callback\n");
      tls_wifi_softap_client_event_register(&(tls_wifi_client_event_cb));

      strncpy((char *)ap_info.ssid, argv[2], 32);
      ap_info.ssid[32] = '\0';
      ap_info.encrypt = IEEE80211_ENCRYT_TKIP_WPA2;
      ap_info.channel = 5;

      ap_info.keyinfo.format = 1;
      ap_info.keyinfo.index = 1;
      ap_info.keyinfo.key_len = strlen(argv[3]);
      strncpy((char *)ap_info.keyinfo.key, argv[3], 63);

      ip_info.ip_addr[0] = 192;
      ip_info.ip_addr[1] = 168;
      ip_info.ip_addr[2] = 1;
      ip_info.ip_addr[3] = 1;
      ip_info.netmask[0] = 255;
      ip_info.netmask[1] = 255;
      ip_info.netmask[2] = 255;
      ip_info.netmask[3] = 0;
      ip_info.dnsname[0] = '\0';
      
      int result = tls_wifi_softap_create(&ap_info, &ip_info);
      shell_printf("Create AP with SSID : %s, key(%d) : %s -> %d\n", ap_info.ssid, ap_info.keyinfo.key_len, ap_info.keyinfo.key, result);
    }
    else if(strcmp(argv[1], "destroy") == 0)
    {
      tls_wifi_softap_client_event_register(NULL);
      tls_wifi_set_oneshot_flag(0);
      tls_wifi_softap_destroy();
      shell_printf("Stopping SOFT AP\n");
    }
    else
    {
      shell_printf("Unknown soft_ap action\n");
    }
  }
  else
  {
    shell_printf("List of soft_ap actions :\nstate\ncreate <SSID> <PWD>\ndestroy\n");
  }
  return 0;
}

int _station(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "scan") == 0)
    {
      tls_wifi_scan_result_cb_register(&(wifi_scan_result_cb));

      if(tls_wifi_scan() == WM_SUCCESS)
      {
        shell_printf("Scanning nearby stations...\n");
      }
      else
      {
        shell_printf("Failed to start wifi scan\n");
      }
    }
    else if(strcmp(argv[1], "state") == 0)
    {
      shell_printf("Station state : %u\n", tls_wifi_get_state());
    }
    else if(strcmp(argv[1], "connect") == 0)
    {
      shell_printf("Connecting to %s with pwd : %s\n", argv[2], argv[3]);
      if(tls_wifi_connect((u8 *)argv[2], strlen(argv[2]), (u8 *)argv[3], strlen(argv[3])) == WM_SUCCESS)
      {
        shell_printf("Connected\n");
      }
      else
      {
        shell_printf("Failed to connect !\n");
      }
    }
    else if(strcmp(argv[1], "disconnect") == 0)
    {
      shell_printf("Disconnecting from current station\n");
      tls_wifi_set_oneshot_flag(0);
      tls_wifi_disconnect();
    }
    else
    {
      shell_printf("Unknown station action\n");
    }
  }
  else
  {
    shell_printf("List of station actions :\nscan\nstate\nconnect <SSID> <PWD>\ndisconnect\n");
  }
  return 0;
}

int _cpu_temp(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  int temperature = adc_temp();

  shell_printf("CPU temp is %d.%03d\n", temperature/1000, temperature%1000);
  return 0;
}

int _wifi(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "off") == 0)
    {
      tls_wifi_softap_destroy();
      tls_wifi_disconnect();
      shell_printf("set one shot flg : %d\n",tls_wifi_set_oneshot_flag(0));
      shell_printf("Stopping WIFI interface\n");
    }
    else if(strcmp(argv[1], "error") == 0)
    {
      shell_printf("Error : %s\n", tls_wifi_get_errinfo(tls_wifi_get_errno()));
    }
    else if(strcmp(argv[1], "promiscuous_on") == 0)
    {
      shell_printf("WiFi promiscuous on\n");
      tls_wifi_data_ext_recv_cb_register(&(tls_wifi_data_ext_recv_cb));
    }
    else if(strcmp(argv[1], "promiscuous_off") == 0)
    {
      shell_printf("WiFi promiscuous off\n");
      tls_wifi_data_ext_recv_cb_register(NULL);
    }
    else if(strcmp(argv[1], "mode") == 0)
    {
      shell_printf("Mode is : %d\n", tls_wifi_get_oneshot_flag());
    }
    else if(strcmp(argv[1], "get_ip") == 0)
    {
      struct netif *netif = tls_get_netif();

      if(netif)
      {
        shell_printf("netif 1\nip addr : %v\nnetmask : %v\ngateway : %v\n", netif->ip_addr.addr,
			  netif->netmask.addr,
			  netif->gw.addr);

        if(netif->next)
        {
          shell_printf("netif 2\nip addr : %v\nnetmask : %v\ngateway : %v\n", netif->next->ip_addr.addr,
			    netif->next->netmask.addr,
			    netif->next->gw.addr);
        }
      }
      else
      {
        shell_printf("No netif yet, connect to sta or create soft_ap !\n");
      }
    }
    else
    {
      shell_printf("Unknown wifi action\n");
    }
  }
  else
  {
    shell_printf("List of wifi actions :\noff\nerror\npromiscuous_on\npromiscuous_off\nmode\nget_ip\n");
  }
  return 0;
}

int _wifi_sleep(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "query") == 0)
    {
      shell_printf("power saving : 0x%X, psm chip sleep : 0x%X\n",
      tls_wifi_get_psflag(),
      tls_wifi_get_psm_chipsleep_flag());
    }
    else if(strcmp(argv[1], "set") == 0)
    {
      
    }
    else
    {
      shell_printf("Unknown wifi_sleep action\n");
    }
    
  }
  else
  {
    shell_printf("List of wifi_sleep actions :\nquery\nset\n");
  }
  return 0;
}

int _pmu(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "sleep") == 0)
    {
      u32 duration = strtoul(argv[2], NULL, 10);
      shell_printf("Going to sleep mode for %u s\n", duration);
      tls_pmu_timer0_start(duration);
      tls_pmu_sleep_start();
      shell_printf("Waking up out of sleep mode\n");
      tls_pmu_timer0_stop();
    }
    else if(strcmp(argv[1], "standby") == 0)
    {
      u32 duration = strtoul(argv[2], NULL, 10);
      shell_printf("Going to standby mode for %u s\n", duration);
      tls_pmu_timer0_start(duration);
      tls_pmu_standby_start();
      shell_printf("Waking up out of standby mode\n");
      tls_pmu_timer0_stop();
    }
    else
    {
      shell_printf("Unknown pmu action\n");
    }
  }
  else
  {
    shell_printf("List of pmu actions :\nsleep <duration(s)>\nstandby <duration(s)>\n");
  }
  return 0;
}

int _rtc(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "get") == 0)
    {
      struct tm rtc_time;
      tls_get_rtc(&rtc_time);

      shell_printf("rtc time is :\n%d:%d:%d %d/%d/%d\n",
      rtc_time.tm_hour,
      rtc_time.tm_min,
      rtc_time.tm_sec,
      rtc_time.tm_mday,
      rtc_time.tm_mon,
      rtc_time.tm_year);
    }
    else if(strcmp(argv[1], "set") == 0)
    {
      struct tm rtc_time;

      rtc_time.tm_hour = strtoul(argv[2], NULL, 10);
      rtc_time.tm_min  = strtoul(argv[3], NULL, 10);
      rtc_time.tm_sec  = strtoul(argv[4], NULL, 10);
      rtc_time.tm_mday  = strtoul(argv[5], NULL, 10);
      rtc_time.tm_mon  = strtoul(argv[6], NULL, 10);
      rtc_time.tm_year  = strtoul(argv[7], NULL, 10);

      shell_printf("Setting rtc to :\n%d:%d:%d %d/%d/%d\nisr callback registered !\n",
      rtc_time.tm_hour,
      rtc_time.tm_min,
      rtc_time.tm_sec,
      rtc_time.tm_mday,
      rtc_time.tm_mon,
      rtc_time.tm_year);

      tls_set_rtc(&rtc_time);
      tls_rtc_isr_register(&(tls_rtc_irq_cb), NULL);
    }
    else if(strcmp(argv[1], "alarm") == 0)
    {
      struct tm rtc_time;

      rtc_time.tm_hour = strtoul(argv[2], NULL, 10);
      rtc_time.tm_min  = strtoul(argv[3], NULL, 10);
      rtc_time.tm_sec  = strtoul(argv[4], NULL, 10);
      rtc_time.tm_mday  = strtoul(argv[5], NULL, 10);
      rtc_time.tm_mon  = strtoul(argv[6], NULL, 10);
      rtc_time.tm_year  = strtoul(argv[7], NULL, 10);

      shell_printf("Setting rtc alarm to :\n%d:%d:%d %d/%d/%d\n",
      rtc_time.tm_hour,
      rtc_time.tm_min,
      rtc_time.tm_sec,
      rtc_time.tm_mday,
      rtc_time.tm_mon,
      rtc_time.tm_year);

      tls_rtc_timer_start(&(rtc_time));
    }
    else
    {
      shell_printf("Unknown rtc action\n");
    }
  }
  else
  {
    shell_printf("List of rtc actions :\nget\nset <h> <m> <s> <d> <m> <y>\nalarm <h> <m> <s> <d> <m> <y>\n");
  }
  return 0; 
}

int _bluetooth(const shell_cmd_t *pcmd, int argc, char *const argv[])
{
  if(argc > 1)
  {
    if(strcmp(argv[1], "enable") == 0)
    {
      shell_printf("Enabling bluetooth : %d\n", demo_bt_enable());
    }
    else if(strcmp(argv[1], "disable") == 0)
    {
      shell_printf("Disabling bluetooth : %d\n", demo_bt_destroy());
    }
    else if(strcmp(argv[1], "start_demo") == 0)
    {
      shell_printf("Starting demo : %d\nUse a BLE app to find the device\n", demo_ble_server_on());
    }
    else if(strcmp(argv[1], "stop_demo") == 0)
    {
      shell_printf("Stopping demo : %d\n", demo_ble_server_off());
    }
    else
    {
      shell_printf("Unknown bluetooth action\n");
    }
  }
  else
  {
    shell_printf("List of bluetooth actions :\nenable\ndisable\nstart_demo\nstop_demo\n");
  }
  return 0; 
}

NANO_SHELL_ADD_CMD(system,
                   _system,
                   "Query system information",
                   "  Use this command to get system information\r\n");
NANO_SHELL_ADD_CMD(reset,
                   _reset,
                   "Reset the system",
                   "  Use this command reset the system\r\n");
NANO_SHELL_ADD_CMD(soft_ap,
                   _soft_ap,
                   "Command to control SOFT AP",
                   "  Use this command to control the SOFT AP subsystem\r\n");
NANO_SHELL_ADD_CMD(station,
                   _station,
                   "Command to control STATION mode",
                   "  Use this command to connect to a WiFi access point\r\n");
NANO_SHELL_ADD_CMD(wifi,
                   _wifi,
                   "Command to control WIFI interface",
                   "  Use this command to control the WIFI interface\r\n");
NANO_SHELL_ADD_CMD(cpu_temp,
                   _cpu_temp,
                   "Command to read the CPU temperature",
                   "  Use this command to read the CPU temperature\r\n");
NANO_SHELL_ADD_CMD(wifi_sleep,
                   _wifi_sleep,
                   "Command to control WiFi sleep",
                   "  Use this command to control WiFi sleep feature\r\n");
NANO_SHELL_ADD_CMD(pmu,
                   _pmu,
                   "Command to control the power management unit",
                   "  Use this command to control power management unit feature\r\n");
NANO_SHELL_ADD_CMD(rtc,
                   _rtc,
                   "Command to query and set up the rtc",
                  "  Use this command to interact with the rtc module\n");
NANO_SHELL_ADD_CMD(bluetooth,
                   _bluetooth,
                   "Command to control bluetooth functionality",
                  "  Use this command to interact use bluetooth\n");
