#include "lottery.h"
#include "main.h"
#include <stdlib.h>
#include <time.h>

void lottery_run(process processes[], int num_processes) {
  unsigned int seed = time(NULL);

  process *ready_queue[num_processes];
  int num_ready = 0;
  int num_processed = 0;
  int num_run = 0;
  cpu_time_t next_free = 0;
  while (num_run < num_processes) {
    // Add new arrivals to ready queue
    for (int i = num_processed;
         i < num_processes && processes[i].arrival <= next_free; i++) {
      ready_queue[num_ready] = &processes[i];
      num_ready++;
      num_processed++;
    }

    // Idle if ready queue is empty
    if (num_ready == 0) {
      next_free = processes[num_processed].arrival;
      continue;
    }

    // Remove random process
    int next_i = rand_r(&seed) % num_ready;
    process *next = ready_queue[next_i];
    num_ready--;
    for (int i = next_i; i < num_ready; i++) {
      ready_queue[i] = ready_queue[i + 1];
    }

    // Run process
    next->num_schedules = 1;
    next->starts = malloc(sizeof(cpu_time_t));
    next->starts[0] = next_free;
    next->durations = malloc(sizeof(cpu_time_t));
    next->durations[0] = next->burst;
    num_run++;

    next_free = next->starts[0] + next->burst;
  }
}

scheduler lottery = (scheduler){.name = "lottery",
                                .description = NULL,
                                .run = lottery_run,
                                .uses_priority = 0};
