#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct argumento {
  int *buffer;
  pthread_mutex_t *mutex;
  int modelos;
};

void* cliente (void* arg){
    struct argumento* a = (struct argumento*) arg;

    long *cantidad=malloc(sizeof(long));
    int modelo = rand()%a->modelos;

    *cantidad=rand()%8+1;

    pthread_mutex_lock(a->mutex);

    if(*cantidad<a->buffer[modelo]){
        a->buffer[modelo]= a->buffer[modelo] - *cantidad;
    }

    pthread_mutex_unlock(a->mutex);

    pthread_exit((void *) cantidad);
    
}

void* proveedor (void* arg){
    struct argumento* a = (struct argumento*) arg;

    long *cantidad=malloc(sizeof(long));
    int modelo = rand()%a->modelos;

    *cantidad=rand()%8+1;

    pthread_mutex_lock(a->mutex);

    a->buffer[modelo]= a->buffer[modelo] + *cantidad;

    pthread_mutex_unlock(a->mutex);

    pthread_exit((void *) cantidad);
    
}

int main(int argc, char **argv){
    pthread_t thr_c[atoi(argv[1])];
    pthread_t thr_p[atoi(argv[2])];
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, NULL);

    srand(time(NULL));
    int num_modelos=atoi(argv[2]);
    long *ret;
    int *buffer=malloc(sizeof(int)*atoi(argv[2]));
    
    for (int i = 0; i < num_modelos; i++)
    {
        buffer[i]=rand()%111+10;
    }
    
    struct argumento arg = {buffer, &mutex, num_modelos};   

    //CREATES
    for (int i = 0; i < atoi(argv[1]); i++)
    {
        pthread_create(&thr_c[i],NULL,(void*)cliente, &arg);
    }
    
    for (int i = 0; i < atoi(argv[2]); i++)
    {
        pthread_create(&thr_p[i],NULL,(void*)proveedor, &arg);
    }

    //JOINS
    for (int i = 0; i < atoi(argv[1]); i++)
    {
        pthread_join(thr_c[i], (void**)&ret);

        printf("CLIENTE COMPRA %ld \n", *ret);  
        free(ret);
    }
    
    for (int i = 0; i < atoi(argv[2]); i++)
    {
        pthread_join(thr_p[i], (void**)&ret);
        printf("PROVEEDOR METE %ld \n", *ret);
        free(ret);
    }

    pthread_mutex_destroy(&mutex);
}