#include "hw_impl_unix.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

static char *fifo_dir = "virt-quad-fifos";
static char *output_pwms[4];

int unix_pwm_output_reset(struct PWMOutputDriver *self) {
  output_pwms[0] = "virt-quad-fifos/pwm-output-motor1";
  output_pwms[1] = "virt-quad-fifos/pwm-output-motor2";
  output_pwms[2] = "virt-quad-fifos/pwm-output-motor3";
  output_pwms[3] = "virt-quad-fifos/pwm-output-motor4";

  mkdir("virt-quad-fifos", 0777);
  int i;
  for (i = 0; i < 4; i += 1) {
    unlink(output_pwms[i]);
    mkfifo(output_pwms[i], 0666);
  }

  return 0;
}

int unix_pwm_output_write(struct PWMOutputDriver *self,
                          unsigned int channel,
                          unsigned long pulse_width_us) {
  char buff[16];
  int fifo = open(output_pwms[channel], O_WRONLY | O_NONBLOCK);
  if (fifo >= 0) {
    sprintf(buff, "%d\0", pulse_width_us);
    int bytes_read = write(fifo, buff, strlen(buff));
  }
  close(fifo);
  return 0;
}