use super::{App, STEPS_PER_PAGE};

impl App {
    pub fn next_step(&mut self) {
        let len = self.current_edit_pattern().length;
        self.editor_ctx.step = (self.editor_ctx.step + 1) % len;
        self.load_step_to_editor();
    }

    pub fn prev_step(&mut self) {
        let len = self.current_edit_pattern().length;
        self.editor_ctx.step = (self.editor_ctx.step + len - 1) % len;
        self.load_step_to_editor();
    }

    pub fn step_up(&mut self) {
        let len = self.current_edit_pattern().length;
        let page_start = (self.editor_ctx.step / STEPS_PER_PAGE) * STEPS_PER_PAGE;
        let steps_on_page = (page_start + STEPS_PER_PAGE).min(len) - page_start;
        let num_rows = steps_on_page.div_ceil(8);
        let steps_per_row = steps_on_page.div_ceil(num_rows);

        if self.editor_ctx.step >= steps_per_row {
            self.editor_ctx.step -= steps_per_row;
        } else {
            self.editor_ctx.step = (self.editor_ctx.step + len - steps_per_row) % len;
        }
        self.load_step_to_editor();
    }

    pub fn step_down(&mut self) {
        let len = self.current_edit_pattern().length;
        let page_start = (self.editor_ctx.step / STEPS_PER_PAGE) * STEPS_PER_PAGE;
        let steps_on_page = (page_start + STEPS_PER_PAGE).min(len) - page_start;
        let num_rows = steps_on_page.div_ceil(8);
        let steps_per_row = steps_on_page.div_ceil(num_rows);

        self.editor_ctx.step = (self.editor_ctx.step + steps_per_row) % len;
        self.load_step_to_editor();
    }

    pub fn select_edit_pattern(&mut self, pattern: usize) {
        self.editor_ctx.pattern = pattern;
        self.editor_ctx.step = 0;
        self.load_step_to_editor();
    }

    pub fn select_edit_bank(&mut self, bank: usize) {
        self.editor_ctx.bank = bank;
        self.editor_ctx.pattern = 0;
        self.editor_ctx.step = 0;
        self.load_step_to_editor();
    }
}
