use crate::Pid;

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LinkState {
    Broken,
    Alive,
}

pub(crate) struct FaultState {
    link_matrix: Vec<Vec<LinkState>>,
}

impl FaultState {
    pub(crate) fn new(size: usize) -> Self {
        Self {
            link_matrix: vec![vec![LinkState::Alive; size]; size],
        }
    }

    pub(crate) fn break_link(&mut self, pid1: Pid, pid2: Pid) {
        self.sym_change_state(pid1, pid2, LinkState::Broken);
    }

    pub(crate) fn isolate(&mut self, pid: Pid) {
        for other in 0..self.link_matrix.len() {
            self.break_link(pid, other);
        }
    }

    pub(crate) fn restore(&mut self, pid: Pid) {
        for other in 0..self.link_matrix.len() {
            self.restore_link(pid, other);
        }
    }

    pub(crate) fn restore_link(&mut self, pid1: Pid, pid2: Pid) {
        self.sym_change_state(pid1, pid2, LinkState::Alive);
    }

    pub(crate) fn is_link_broken(&self, pid1: Pid, pid2: Pid) -> bool {
        self.link_matrix[pid1][pid2] == LinkState::Broken
    }

    fn sym_change_state(&mut self, pid1: Pid, pid2: Pid, state: LinkState) {
        self.link_matrix[pid1][pid2] = state;
        self.link_matrix[pid2][pid1] = state;
    }
}
