//! Step and bank/pattern cursor navigation.

use cagire_project::{MAX_BANKS, MAX_PATTERNS};
use tachyonfx::Motion;

use super::App;

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 spp = self.editor_ctx.steps_per_page.get();
        let page_start = (self.editor_ctx.step / spp) * spp;
        let steps_on_page = (page_start + spp).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 spp = self.editor_ctx.steps_per_page.get();
        let page_start = (self.editor_ctx.step / spp) * spp;
        let steps_on_page = (page_start + spp).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();
    }

    pub fn navigate_pattern(&mut self, delta: i32) {
        let cur = self.editor_ctx.pattern as i32;
        self.editor_ctx.pattern = (cur + delta).rem_euclid(MAX_PATTERNS as i32) as usize;
        self.editor_ctx.step = 0;
        self.load_step_to_editor();
        let direction = if delta > 0 { Motion::UpToDown } else { Motion::DownToUp };
        self.ui.show_nav_indicator(500, direction);
    }

    pub fn navigate_bank(&mut self, delta: i32) {
        let cur = self.editor_ctx.bank as i32;
        self.editor_ctx.bank = (cur + delta).rem_euclid(MAX_BANKS as i32) as usize;
        self.editor_ctx.step = 0;
        self.load_step_to_editor();
        let direction = if delta > 0 { Motion::LeftToRight } else { Motion::RightToLeft };
        self.ui.show_nav_indicator(500, direction);
    }
}
