#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <signal.h>

void sig_handler(int signo)
{
  if (signo == SIGINFO)
    printf("received SIGINFO\n");
}

int main(int argc, const char *argv[])
{
  char inputMinutes[6];
  char inputText[256];

  // register signal handler
  if (signal(SIGINFO, sig_handler) == SIG_ERR)
      printf("\ncan't catch SIGINFO\n");

  FILE *fp;

  // READ INPUT MINUTES
  fp = popen("echo | dmenu -p \"Set timer (minutes): \" -i -fn \"Droid Sans Mono for Powerline-14\" -nb \"#181818\" -sb \"#282828\"", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }
  while (fgets(inputMinutes, sizeof(inputMinutes)-1, fp) != NULL) {
    printf("%s", inputMinutes);
  }
  pclose(fp);

  fp = popen("echo | dmenu -p \"Set timer (text): \" -i -fn \"Droid Sans Mono for Powerline-14\" -nb \"#181818\" -sb \"#282828\"", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }
  while (fgets(inputText, sizeof(inputText)-1, fp) != NULL) {
    printf("%s", inputText);
  }
  pclose(fp);

  inputText[strcspn(inputText, "\n")] = 0;
  if(!strlen(inputText)) {
    strcat(inputText, "Beep Beep");
  }

  int delaySeconds = atoi(inputMinutes) * 60;
  printf("Timer set for %i minute(s) with text \"%s\"\n", delaySeconds / 60, inputText);

  int elapsedSeconds = 1;
  while((delaySeconds + 1) > elapsedSeconds) {
    elapsedSeconds = elapsedSeconds + 1;
    nanosleep(&(struct timespec){.tv_sec=1}, NULL);
  }
  
  char command[512];

  strcpy(command, "i3-nagbar -m \"Timer: ");
  strcat(command, inputText);
  strcat(command, "!\" -t warning -f \"-*-helvetica-bold-r-*-*-20-*-*-*-*-*-*-*\"");
  system(command);

  return 0;
}
