use crate::{
    id::{RecRef, SegmentId},
    journal::records::InsertRecord,
};
use std::vec::IntoIter;

pub struct TransactionInsertScanner {
    inserted: Vec<InsertRecord>,
    segment: SegmentId,
}
impl TransactionInsertScanner {
    pub fn new(inserted: Vec<InsertRecord>, segment: SegmentId) -> Self {
        Self { inserted, segment }
    }
}

pub struct TransactionInsertIterator {
    iter: IntoIter<InsertRecord>,
    segment: SegmentId,
}

impl IntoIterator for TransactionInsertScanner {
    type Item = RecRef;
    type IntoIter = TransactionInsertIterator;

    fn into_iter(self) -> Self::IntoIter {
        let iter: IntoIter<InsertRecord> = self.inserted.into_iter();
        TransactionInsertIterator {
            iter,
            segment: self.segment,
        }
    }
}

impl Iterator for TransactionInsertIterator {
    type Item = RecRef;
    fn next(&mut self) -> Option<RecRef> {
        loop {
            let next = self.iter.next();
            if let Some(rec) = next {
                if rec.segment == self.segment {
                    return Some(rec.recref);
                }
            } else {
                return None;
            }
        }
    }
}
