use crate::{Session, SJFLError};
use crate::parse::{Assignment, Import};

pub enum Statement {
    Assignment(Assignment),
    Import(Import),
    NOP
}

impl Statement {

    pub fn execute(&self, session: &mut Session) -> Result<(), SJFLError> {

        match self {
            Statement::Assignment(Assignment { lhs, rhs }) => {
                let mut rhs = rhs.clone();
                rhs.substitute_vars(session)?;

                session.vars.insert(lhs.index, rhs);
            },
            Statement::Import(Import { file_name }) => {
                let file_name = match session.get_string_from_index(*file_name) {
                    Some(s) => String::from_utf8_lossy(&s).to_string(),
                    None => {
                        return Err(SJFLError::MalformedString(*file_name));
                    }
                };

                crate::execute_file(&file_name, session).map_err(|(e, _)| e)?;
            }
            Statement::NOP => {}
        }

        Ok(())
    }

}