#include "sjf.h"
#include "main.h"
#include <stdlib.h>

void sjf_run(process processes[], int num_processes) {
  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 process with shortest burst
    int shortest = 0;
    for (int i = 0; i < num_ready; i++) {
      if (ready_queue[i]->burst < ready_queue[shortest]->burst) {
        shortest = i;
      }
    }
    process *next = ready_queue[shortest];
    num_ready--;
    for (int i = shortest; 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 sjf = (scheduler){.name = "sjf",
                            .description = "Shortest Job First",
                            .run = sjf_run,
                            .uses_priority = 0};
