#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <unistd.h>
#include <termios.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include "structure.h"
#include "base.h"
#include "cars.h"

const double PI = 3.14159;

ptf get_position(int nPl, int nTotPl) {
    double theta = (2.0*MAX_THETA_SPAWN*nPl/((nTotPl-1==0)?(1):(nTotPl-1)) - 1.0*MAX_THETA_SPAWN);
    //printf("%d --> %lf", nPl, theta);
    return (ptf){
        .fx = ROOM_SIZE/2.0+cos(theta*PI/180.0 +PI/2.0*(START_DIR+1))*ROOM_SIZE/3.3,
        .fy = ROOM_SIZE/2.0+sin(theta*PI/180.0 +PI/2.0*(START_DIR+1))*ROOM_SIZE/3.3
    };
}

car* init_car(int nPl, int nTotPl) {
    car* res = malloc(sizeof(car));
    res->itm = NULL;
    res->nCoins = 0;
    
    res->pos = get_position(nPl, nTotPl);
    res->lastPos = (ptf){.fx = res->pos.fx, .fy = res->pos.fy};

    res->chx = START_CHY;
    res->lastChx = START_CHY;
    res->chy = START_CHX;
    res->lastChy = START_CHX;

    res->vel = (ptf){.fx = 0.0, .fy = 0.0};
    //double theta = (2.0*MAX_THETA_SPAWN*nPl/((nTotPl-1==0)?(1):(nTotPl-1)) - 1.0*MAX_THETA_SPAWN);
    //res->vel = (ptf){.fx = (rand()%100)/100.0*2.0*MAX_SPEED, .fy = (rand()%100-50.0)/100.0*2.0*MAX_SPEED};
    return res;
}

void place_car(car* c, double x, double y) {
    c->pos.fx = x;
    c->pos.fy = y;
}

void set_speed_car(car* c, double vx, double vy) {
    c->vel.fx = vx;
    c->vel.fy = vy;
}

void destroy_car(car* c) {
    free(c);
}

// ------------------------------------------------------------ //