pub mod capabilities;
pub mod priority;
pub mod proc;

use crate::scheduler::capabilities::Capabilities;
use crate::{arch::generate_process_pass, stdio::StdIO};
use kernel::proccess::PID;
use priority::Priority;
use proc::Process;

pub static SCHEDULER: spin::Mutex<Scheduler> = spin::Mutex::new(Scheduler::new());

/// Add additional wake conditions to the list
#[derive(Clone, Debug)]
pub enum WakeCondition {
    /// Wake when the process has been blocked for a certain amount of time  
    TimerInterrupt(u64),
    SocketRead(PID),
    SocketWrite(PID),
    SocketOpen(PID),
    SocketClose(PID),
    // HardwareEvent,
}

// NOTE: Define what is a sleeping process in the context of the ableOS kernel.
// Blocked processes are processes that are waiting for a certain event to occur.
#[derive(Clone, Debug)]
pub struct BlockedProcess {
    pub pid: PID,
    pub wake_condition: WakeCondition,
}

pub struct Scheduler {
    pub free_pid: PID,
    pub process_exec_time: u64,
    pub execution_queue: Vec<Process>,
    pub sleeping_queue: Vec<BlockedProcess>,
    pub blocked_queue: Vec<BlockedProcess>,
    // All timed processes sorted by wake time
}

impl Scheduler {
    /// Create a new scheduler
    pub const fn new() -> Self {
        Self {
            free_pid: 0,
            process_exec_time: 0,
            execution_queue: Vec::new(),
            sleeping_queue: Vec::new(),
            blocked_queue: Vec::new(),
        }
    }

    /// Change the current process to the next process in the list
    pub fn next_process(&mut self) {
        self.process_exec_time = 0;
        let previous_task = self.execution_queue[0].clone();
        self.execution_queue.remove(0);
        self.execution_queue.push(previous_task);
    }

    pub fn add_process(&mut self, mut process: Process) {
        process.pid = self.free_pid;
        self.free_pid += 1;
        self.execution_queue.push(process);
    }

    pub fn new_process(
        &mut self,
        capabilities: Capabilities,
        priority: Priority,
        working_dir: String,
        stdio: StdIO,
    ) -> Process {
        Process {
            pid: 0,
            priority,
            working_dir,
            stdio,
            password: generate_process_pass(),
            capabilities,
        }
    }

    pub fn sleep_process(&mut self, process: &mut Process) {
        let sleeping_process = BlockedProcess {
            pid: process.pid,
            wake_condition: WakeCondition::TimerInterrupt(0),
        };

        self.sleeping_queue.push(sleeping_process);
        self.execution_queue.remove(0);
    }
}
