#include "GSAT/GSAT.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <mpi.h>
#include "color.h"

using namespace std;

void help(char* prog) {
    fprintf(stderr, "usage: mpirun -n int %s -i file.cnf\n\t-n Number of process to use\n\t-i CNF file to solve\n", prog);
    exit(1);
}

int main(int argc, char* argv[]) {

    if(argc < 3) {
        help(argv[0]);
    }

    //Init MPI
    int world_size;
    int world_rank;
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

    GSAT* gsat = new GSAT();
    gsat->setParameters(argc,argv);
    gsat->initialize();
    if(world_rank == 0) {
        printf("c nbProcessors: %d\n", world_size);
        printf("c nbVariables: %d\n",gsat->getNbVariables());
        printf("c nbClauses: %d\n",gsat->getNbClauses());
    }
    double startTime = gsat->realTime();
    srand(getpid());

    //Attente d'un message de fin
    int syncBuff;
    MPI_Request sync, send;
    MPI_Irecv(&syncBuff, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &sync);

    //Calcul  
    bool end = false;
    bool stop = false;
    while(!end && !stop){
        //Pour eviter que les processeurs effectue tous les meme calculs
        int fill = rand() % 4 + 2;
        int h = rand() % 7;
        end = gsat->start(fill, h);
        //Affiche calcul
        if(end) {
            printf(CYAN);
        }
        printf("c [processor:%d][iteration:%5d][fill:%d][heuristic:%d]Satisfied clauses (begin: %d)(end:%d)\n",
            world_rank,
            gsat->getNbIterations(),
            gsat->getHeuristicFill(),
            gsat->getHeuristicSolve(),
            gsat->getNbSatisfiedClausesFill(),
            gsat->getNbSatisfiedClausesSolve());
        if(end) {
            printf(RESET);
        }
        //Regarde si quelqu'un a trouver
        int flag;
        MPI_Test(&sync, &flag, MPI_STATUS_IGNORE);
        if(flag) {
            stop = true;
        }
    }

    //Si on est le processus qui à trouvé
    if(end) {
        //Avertit les autres
        for(int i = 0; i < world_size; i++) {
            MPI_Isend(&world_rank, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &send);
        }
        //Attend la fin des autres processus
        for(int i = 0; i < world_size; i++) {
            if(i != world_rank) {
                int buff;
                MPI_Recv(&buff, 1, MPI_INT, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            }
        }
        //Affiche le resultat
        printf("--------------------------------------------------------------------------------------------\n");
        printf(GREEN);
        printf("s %s\n",end?"SATISFIABLE":"NOT FOUND");
        printf(YELLOW);
        printf("c real time : %.4f seconds\n", gsat->realTime() - startTime);
        printf("c [processor:%d][iteration:%5d][fill:%d][heuristic:%d]Satisfied clauses (begin: %d)(end:%d)\n",
            world_rank,
            gsat->getNbIterations(),
            gsat->getHeuristicFill(),
            gsat->getHeuristicSolve(),
            gsat->getNbSatisfiedClausesFill(),
            gsat->getNbSatisfiedClausesSolve());
        printf(RESET);
    } else {
        //Indique au processus qui a trouvé que ce processus a finit de travailler
        int buff = 1;
        MPI_Send(&buff, 1, MPI_INT, syncBuff, 0, MPI_COMM_WORLD);
    }

    MPI_Finalize();    

}