use std::io;
use std::clone::Clone;
use stage::TransformationStage;
use result::StageActions;

pub struct TransformationPipeline<T: Clone> {

    stages: Vec<Box<TransformationStage<T>>>,

}

impl<T: Clone> TransformationPipeline<T> {
    pub fn new(stages: Vec<Box<TransformationStage<T>>>) -> TransformationPipeline<T> {
        TransformationPipeline {
            stages: stages,
        }
    }

    pub fn run(&self, initial_data: T) -> Result<T, io::Error> {

        let mut skip_stages: u8 = 0;
        let mut current_stage: u8 = 0;
        let mut current_data: T = initial_data;

        for stage in &self.stages {

            if skip_stages > 0 {
                skip_stages = skip_stages - 1;
                current_stage = current_stage + 1;
                continue;
            }

            let stage_result: StageActions<T> = stage.run(current_data.clone())?;
            match stage_result {
                StageActions::Abort => {
                    return Err(io::Error::new(io::ErrorKind::Other, "Stage aborted."));
                },
                StageActions::Skip => {
                },
                StageActions::Next(stage_result_data) => {
                    current_data = stage_result_data;
                },
                StageActions::Jump(stage_count, stage_result_data) => {
                    skip_stages = stage_count;
                    current_data = stage_result_data;
                },
                StageActions::Finish(stage_result_data) => {
                    return Ok(stage_result_data);
                },
            }

            current_stage = current_stage + 1;
        }
        Ok(current_data)
    }
}
