use std::path::PathBuf;

use crate::model::{MAX_BANKS, MAX_PATTERNS};
use crate::model::Project;

pub struct ProjectState {
    pub project: Project,
    pub file_path: Option<PathBuf>,
    dirty_patterns: [[bool; MAX_PATTERNS]; MAX_BANKS],
    dirty_count: usize,
}

impl Default for ProjectState {
    fn default() -> Self {
        let mut state = Self {
            project: Project::default(),
            file_path: None,
            dirty_patterns: [[false; MAX_PATTERNS]; MAX_BANKS],
            dirty_count: 0,
        };
        state.mark_all_dirty();
        state
    }
}

impl ProjectState {
    pub fn mark_dirty(&mut self, bank: usize, pattern: usize) {
        if !self.dirty_patterns[bank][pattern] {
            self.dirty_patterns[bank][pattern] = true;
            self.dirty_count += 1;
        }
    }

    pub fn mark_all_dirty(&mut self) {
        self.dirty_patterns = [[true; MAX_PATTERNS]; MAX_BANKS];
        self.dirty_count = MAX_BANKS * MAX_PATTERNS;
    }

    pub fn take_dirty(&mut self) -> Vec<(usize, usize)> {
        if self.dirty_count == 0 {
            return Vec::new();
        }
        let mut result = Vec::with_capacity(self.dirty_count);
        for (bank, patterns) in self.dirty_patterns.iter_mut().enumerate() {
            for (pattern, dirty) in patterns.iter_mut().enumerate() {
                if *dirty {
                    *dirty = false;
                    result.push((bank, pattern));
                }
            }
        }
        self.dirty_count = 0;
        result
    }
}
