use crate::{address::Address, id::RecRef};
pub struct SegmentPageIterator {
    cur_page: u64,
    next_page: u64,
    per_page_iterator: Vec<(u32, bool)>,
    iter_pos: usize,
    include_deleted: bool,
}

impl SegmentPageIterator {
    pub fn new(first_page: u64) -> Self {
        Self {
            cur_page: first_page,
            next_page: first_page,
            per_page_iterator: vec![],
            iter_pos: 0,
            include_deleted: false,
        }
    }
    pub fn snapshot(first_page: u64) -> Self {
        Self {
            cur_page: first_page,
            next_page: first_page,
            per_page_iterator: vec![],
            iter_pos: 0,
            include_deleted: true,
        }
    }

    pub fn next(&mut self, address: &Address) -> Option<RecRef> {
        // This loop is needed because some pages may be empty
        loop {
            if self.iter_pos < self.per_page_iterator.len() {
                let (pos, exists) = self.per_page_iterator[self.iter_pos];
                self.iter_pos += 1;
                if exists || self.include_deleted {
                    break Some(RecRef::new(self.cur_page, pos));
                }
            } else if self.next_page != 0 {
                self.cur_page = self.next_page;
                if let Ok((next_page, elements)) = address.scan_page_all(self.cur_page) {
                    self.next_page = next_page;
                    self.per_page_iterator = elements;
                    self.iter_pos = 0;
                }
            } else {
                break None;
            }
        }
    }
}
