/*
This is a personal academic project. Dear PVS-Studio, please check it.
PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*/
#define _POSIX_C_SOURCE 2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "error.h"

#define MAX_SIZE 300
#define COMMAND_MAX_SIZE 400

void runCommand(char *, char *);
void printOutput(char *, char *);

int main(int argc, char *argv[]) {
    setvbuf(stdout, NULL, _IONBF, 0);

    char output[MAX_SIZE];
    char input[MAX_SIZE];

    /*
    // Falta manejo de errores de fgets!
    while (fgets(input, MAX_SIZE, stdin)) {
        input[strcspn(input, "\n")] = '\0';
        runCommand(input, output);
        printOutput(output, input);
    }
    */

    int readChars;
    while ((readChars = read(STDIN_FILENO, input, MAX_SIZE) != 0)) {
        if (readChars < 0)
            printSystemError("slave.c -- read()");

        char * inputLine = strtok(input, "\n");
        while (inputLine != NULL) {
            runCommand(inputLine, output);
            printOutput(output, inputLine);
            inputLine = strtok(NULL, "\n");
        }
    }


    // int saved_flags = fcntl(fd, F_GETFL);
    // fcntl(fd, F_SETFL, saved_flags & ~O_NONBLOCK);
}

void runCommand(char * inputLine, char * output) {
    char command[COMMAND_MAX_SIZE];
    //sprintf(command, "minisat %s | grep -o -e \"Number of .*[0-9]\\+\" -e \"CPU time.*\" -e \".*SATISFIABLE\" |  awk '{if (NR == 1) {print $4} ; if (NR == 2) {print $4} ; if (NR == 3) {print $4 $5} ; if (NR == 4) {print $1}}'", inputLine);
    sprintf(command, "minisat %s | grep -o -e \"Number of .*[0-9]\\+\" -e \"CPU time.*\" -e \".*SATISFIABLE\" | awk '{if (NR == 1) {printf \"Cantidad de variables: \" $4 \" - \"} ; if (NR == 2) {printf \"Cantidad de cláusulas: \" $4 \" - \"} ; if (NR == 3) {printf \"Tiempo de procesamiento: \" $4 $5 \" - \"} ; if (NR == 4) {printf \"Resultado: \" $1}}'", inputLine);
    // Pequeña ayuda para popen: https://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output
    FILE * fp;
    if (!(fp = popen(command, "r")))
	    printSystemError("slave.c -- popen()");

    // Ver manejo de errores de fread!
    size_t outputLength = fread(output, sizeof(char), MAX_SIZE, fp);
    output[outputLength] = '\0';

    if (ferror(fp))
        printSystemError("slave.c -- ferror()");

    if (pclose(fp) < 0)
	    printSystemError("slave.c -- pclose()");

}

void printOutput(char * output, char * fileName) {
    printf("Nombre del archivo: %s - %s - Id del esclavo: %d\n", fileName, output, getpid());

    // int saved_flags = fcntl(fd, F_GETFL);
    // fcntl(fd, F_SETFL, saved_flags & O_NONBLOCK);
}