#include <stddef.h>
#include <stdint.h>
#include <ulib.h>
#include "macros.h"

struct {
  char *specificproc;
  int32_t pid;
} PCTL_LS_CONFIG = {
  .specificproc = NULL,
  .pid = -1,
};

static Arg ARGS[] = {
  ARG("-proc", ARG_STRING, &PCTL_LS_CONFIG.specificproc),
  ARG("-pid", ARG_INT, &PCTL_LS_CONFIG.pid),
  ARG_END(),
};

void pctl_ls(void) {
  int32_t ret;
  if ((ret = parse_args(SUBCMD_ARGS(), SUBCMD_ARGSLEN(), ARGS)) < 0) {
    uprintf("pctl ls: Could not parse args: %d\n", ret);
    return;
  }

  static const char *states[] = {"embryo", "ready", "zombie", "waiting", "died"};

  int32_t procslen = proc_listsize();

  char *namebuf = umalloc(34);
  char *membuf = umalloc(20);
  
  uprintf("%-30s %s %-15s %-8s %-25s\n", "NAME", "PID", "MEMORY", "STATE", "UPTIME");
  for (size_t i = 0; i < (size_t)procslen; i++) {
    ProcStat stat; ZERO(&stat);

    string_memset(namebuf, 0, 34);
    string_memset(membuf, 0, 20);

    int32_t r = proc_stat(i, &stat);
    if (r == E_OK) {
      if (PCTL_LS_CONFIG.specificproc != NULL
       && string_strcmp(stat.name, PCTL_LS_CONFIG.specificproc) != 0) {
        continue;
      }

      if (PCTL_LS_CONFIG.pid != -1 && stat.pid != (uint64_t)PCTL_LS_CONFIG.pid) {
        continue;
      }

      string_memcpy(namebuf, stat.name, 30);
      namebuf[31] = namebuf[32] = namebuf[33] = '.';

      // Too big format string causes a stack overflow. This is an issue with printf ;(
      uprintf("%-30s %-3lu %-15s ",
              namebuf,
              stat.pid,
              human_size(stat.usemem, membuf, 20)
            );
      uprintf("%-8s ", states[stat.state]);

      Time time1;
      time(&time1);
      timeunix_t now = time_tounix(&time1);
      timeunix_t procspawn = time_tounix(&stat.time);
      timeunix_t diff = now - procspawn;

      char uptimebuf[100];

      uint32_t hrs = diff / 3600;
      uint32_t mins = (diff % 3600) / 60;
      uint32_t secs = diff % 60;

      usprintf(uptimebuf, "%us %umin %uh", secs, mins, hrs);

      uprintf("%-25s ", uptimebuf);

      uprintf("\n");
    }
  }
}
