/*************************************************  
  File name     : mw_unittest.c
  Module        : 
  Author        : amir 
  Version       : 0.1   
  Created on    : 2023-02-07  
  Description   :
      Data structure and function definitions required by the socket interface

  Modify History:   
  1. Date:        Author:         Modification:
*************************************************/
#include "mw_mmc.h"
#include "mw_unittest.h"
#include "hlog.h"
#include "util.h"


#define INSUT_UNITTEST_SHOWHOW -2

static int32_t unittest_help(unittest_cmd *cmd_info, uint8_t cmd_cnt)
{
    uint8_t i = 0;
    if(cmd_info == NULL)
    {
        return EINVAL;
    }

    hlogi("Command List:");
    for(i=0; i<cmd_cnt; i++)
    {
        hlogi("  %s - %s", cmd_info[i].cmd_name, cmd_info[i].cmd_help);
    }
    return 0;
}

static int32_t unittest_run_cmd(unittest_cmd *cmd_info, uint8_t cmd_cnt, int32_t argc, char **argv)
{
    uint8_t i = 0;
    int32_t rval = 0;
    if(argc > 0 && argv != NULL)
    {
        for(i=0; i<cmd_cnt; i++)
        {
            if(strcmp(argv[0], cmd_info[i].cmd_name) == 0)
            {
                if(cmd_info[i].exec_func != NULL)
                {
                    rval = cmd_info[i].exec_func(argc-1, &argv[1]);
                    if(rval == INSUT_UNITTEST_SHOWHOW)
                    {
                        unittest_help(cmd_info, cmd_cnt);
                    }
                    else if(rval != 0)
                    {
                        hloge("Rum cmd fail [ %s ] (0x%x)", argv[0], rval);
                    }
                    return rval;
                }
                else if(cmd_info[i].next_cmd != NULL)
                {
                    return unittest_run_cmd(cmd_info[i].next_cmd, cmd_info[i].next_cmd_cnt, argc-1, &argv[1]);
                }
            }
        }
    }
    unittest_help(cmd_info, cmd_cnt);
    return INSUT_UNITTEST_SHOWHOW;
}

int32_t unittest_shell_entry(int32_t argc, char **argv)
{
    unittest_cmd *cmds;
    uint32_t cnt = unittest_get(&cmds);
    return unittest_run_cmd(cmds, cnt, argc, argv);                       
}

void unittest(uint32_t argc, char **argv)
{
    unittest_shell_entry(argc, argv);
}

int32_t unittest_test()
{
    char *args0[]={}; /* print all */
    unittest_shell_entry(sizeof(args0)/sizeof(char *), args0);
    
    char *args[]={"device", "gpio", "output", "88", "0"};
    //char *args[]={"device", "gpio"}; 提示help
    unittest_shell_entry(sizeof(args)/sizeof(char *), args);

    char *args2[]={"media", "debug"};
    // char *args2[]={"media"}; 提示help
    unittest_shell_entry(sizeof(args2)/sizeof(char *), args2);

    char *args3[]={"main",  "main"};
    unittest_shell_entry(sizeof(args3)/sizeof(char *), args3);
}

