use data::tables::ProcedureConfigID;

use super::{ProcedureAction, ProcedureBase, ProcedureError, ProcedureState, ProcedureType};

pub struct ProcedurePlotPlay {
    id: ProcedureConfigID,
    state: ProcedureState,
}

impl ProcedurePlotPlay {
    pub fn new(id: ProcedureConfigID) -> Self {
        Self {
            id,
            state: ProcedureState::Init,
        }
    }
}

impl ProcedureBase for ProcedurePlotPlay {
    fn id(&self) -> ProcedureConfigID {
        self.id
    }

    fn procedure_type(&self) -> ProcedureType {
        ProcedureType::PlotPlay
    }

    fn on_action(&mut self, action: ProcedureAction) -> Result<ProcedureState, ProcedureError> {
        match action {
            ProcedureAction::PerformTrigger => {
                (self.state == ProcedureState::Init)
                    .then_some(())
                    .ok_or(ProcedureError::InvalidState(action, self.state))?;

                self.state = ProcedureState::Running;
            }
            ProcedureAction::PerformEnd => {
                (self.state == ProcedureState::Running)
                    .then_some(())
                    .ok_or(ProcedureError::InvalidState(action, self.state))?;

                self.state = ProcedureState::Finish
            }
            _ => {
                return Err(ProcedureError::UnsupportedAction(
                    action,
                    self.procedure_type(),
                ))
            }
        }

        Ok(self.state)
    }

    fn is_finished(&self) -> bool {
        self.state >= ProcedureState::Running
    }
}
