use crossbeam_channel::Sender;

use crate::engine::{PatternChange, PatternSnapshot, SeqCommand, StepSnapshot};

use super::App;

impl App {
    pub fn flush_queued_changes(&mut self, cmd_tx: &Sender<SeqCommand>) {
        for staged in self.playback.queued_changes.drain(..) {
            match staged.change {
                PatternChange::Start { bank, pattern } => {
                    let _ = cmd_tx.send(SeqCommand::PatternStart {
                        bank,
                        pattern,
                        quantization: staged.quantization,
                        sync_mode: staged.sync_mode,
                    });
                }
                PatternChange::Stop { bank, pattern } => {
                    let _ = cmd_tx.send(SeqCommand::PatternStop {
                        bank,
                        pattern,
                        quantization: staged.quantization,
                    });
                }
            }
        }
    }

    pub fn send_mute_state(&self, cmd_tx: &Sender<SeqCommand>) {
        let _ = cmd_tx.send(SeqCommand::SetMuteState {
            muted: self.mute.muted.clone(),
            soloed: self.mute.soloed.clone(),
        });
    }

    pub fn flush_dirty_patterns(&mut self, cmd_tx: &Sender<SeqCommand>) -> bool {
        let dirty = self.project_state.take_dirty();
        let had_dirty = !dirty.is_empty();
        for (bank, pattern) in dirty {
            let pat = self.project_state.project.pattern_at(bank, pattern);
            let snapshot = PatternSnapshot {
                speed: pat.speed,
                length: pat.length,
                steps: pat
                    .steps
                    .iter()
                    .take(pat.length)
                    .map(|s| StepSnapshot {
                        active: s.active,
                        script: s.script.clone(),
                        source: s.source,
                    })
                    .collect(),
                quantization: pat.quantization,
                sync_mode: pat.sync_mode,
            };
            let _ = cmd_tx.send(SeqCommand::PatternUpdate {
                bank,
                pattern,
                data: snapshot,
            });
        }
        had_dirty
    }
}
