#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <time.h>

#include "networld.h"
#include "controlpanel.h"
#include "random-map.h"

#include "raylib.h"


double randfrom(double min, double max) 
{
    double range = (max - min); 
    double div = RAND_MAX / range;
    return min + (rand() / div);
}

double dist(Node node1, Node node2){
    return(sqrt( (node2.position.x - node1.position.x)*(node2.position.x - node1.position.x) + (node2.position.y - node1.position.y)*(node2.position.y - node1.position.y) ));
}
void Random_map(NetWorld * world)
{
    int nbNode = world->size;
    float randomX, randomY;
/* Intializes random number generator */    
    srand(time(NULL));
/* Print 5 random numbers from -15.00 to 15.00 */
    for( int i = 0 ; i < nbNode ; i++ ) {
        double randomX = randfrom(-15.0, 15.0);
        double randomY = randfrom(-15.0, 15.0);
        char * name;
        name= malloc(sizeof(int));
        sprintf(name, "name : %d", i);
        Node_set( &(world->nodes[i]), (Vector2){randomX, randomY}, RED, name);
        printf("%f\n", randomX);
        printf("%f\n", randomY);
   }
    //Gabriel graph sort
    for( int i = 0; i <nbNode-1 ; i++){
        for( int j = i+1; j <nbNode ; j++){
            int compteurPointDansLeCercle = 0;
            float xm = 0.5*(world->nodes[i].position.x + world->nodes[j].position.x);
            float ym = 0.5*(world->nodes[i].position.y + world->nodes[j].position.y);
            float distCenterOfij = sqrt((xm - world->nodes[i].position.x)*(xm - world->nodes[i].position.x) + (ym - world->nodes[i].position.y)*(ym - world->nodes[i].position.y));
            printf("xm : %f\n", xm);
            printf("ym : %f\n", ym);
            printf("distCenterOfij : %f\n", distCenterOfij);
            printf("dist %d%d : %f\n", i ,j ,dist((world->nodes[i]),world->nodes[j]));
            for(int k = 0 ; k < nbNode ; k++){
                printf(" dist center - Node k %f\n", sqrt((world->nodes[k].position.x - xm)*(world->nodes[k].position.x - xm) + (world->nodes[k].position.y - ym)*(world->nodes[k].position.y - ym)));
                if( sqrt((world->nodes[k].position.x - xm)*(world->nodes[k].position.x - xm) + (world->nodes[k].position.y - ym)*(world->nodes[k].position.y - ym)) < distCenterOfij -0.05){
                    compteurPointDansLeCercle ++;
                }
            }
            printf("compteurPointDansLeCercle : %i\n", compteurPointDansLeCercle);
            if(compteurPointDansLeCercle == 0){
                NetWorld_biconnect(world, i, j);
            }
                
               
        }
    } 
}