#include "test_shell_commander.h"
#include "commander.h"
#include "tester.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

TestFuncResult test_commander_cmd_success(void) {
  CMDResult result = wapp_shell_commander_execute(SHELL_OUTPUT_DISCARD, NULL, 0, "echo", "hello world");
  bool succeeded   = result.exited && result.exit_code == EXIT_SUCCESS &&
                     result.error == SHELL_ERR_NO_ERROR;

  return wapp_tester_result(succeeded);
}

TestFuncResult test_commander_cmd_failure(void) {
  CMDResult result = wapp_shell_commander_execute(SHELL_OUTPUT_DISCARD, NULL, 0, "grep");
  bool failed      = result.exited && result.exit_code != EXIT_SUCCESS &&
                     result.error == SHELL_ERR_NO_ERROR;

  return wapp_tester_result(failed);
}

TestFuncResult test_commander_cmd_out_buf_success(void) {
  char buf[64]             = {0};
  char expected_output[64] = {0};
  const char *msg          = "hello world";
  u64 length               = strlen(msg);
  snprintf(expected_output, length + 2, "%s\n", msg);

  CMDResult result = wapp_shell_commander_execute(SHELL_OUTPUT_CAPTURE, buf, 64, "echo", msg);
  bool succeeded   = result.exited && result.exit_code == EXIT_SUCCESS &&
                     result.error == SHELL_ERR_NO_ERROR &&
                     strncmp(buf, expected_output, length) == 0;

  return wapp_tester_result(succeeded);
}

TestFuncResult test_commander_cmd_out_buf_failure(void) {
  char buf[4]      = {0};
  const char *msg  = "hello world";
  u64 length       = strlen(msg);
  CMDResult result = wapp_shell_commander_execute(SHELL_OUTPUT_CAPTURE, buf, 4, "echo", msg);
  bool failed      = !result.exited && result.exit_code != EXIT_SUCCESS &&
                     result.error == SHELL_ERR_OUT_BUF_FULL && strncmp(buf, msg, length) != 0;

  return wapp_tester_result(failed);
}