from future.moves.itertools import zip_longest
from ableton.v2.control_surface.components import MixerComponent

from .channel_strip import ColoredChannelStripComponent

class ExquisMixerComponent(MixerComponent):
	"A MixerComponent that uses its Mute buttons to show the track level, and that allows to set the send controls for each track"

	def __init__(self, *a, **k):
		super(ExquisMixerComponent, self).__init__(channel_strip_component_type=ColoredChannelStripComponent, *a, **k)
		self._should_show_track_level = False
		self._can_show_track_level = False

	def set_send_a_controls(self, controls):
		self._set_send_controls(controls, 0)

	def set_send_b_controls(self, controls):
		self._set_send_controls(controls, 1)

	def _set_send_controls(self, controls, send_index):
		if controls:
			for index, control in enumerate(controls):
				if control:
					self.channel_strip(index).set_send_controls((None,) * send_index + (control,))
		else:
			for strip in self._channel_strips:
				strip.set_send_controls(None)
	
	def set_mute_buttons(self, buttons):
		super().set_mute_buttons(buttons)
		self._should_show_track_level = buttons != None
		self.update()

	def disconnect(self):
		self._should_show_track_level = False
		self._can_show_track_level = False
		super().disconnect()
	
	def update(self):
		super(ExquisMixerComponent, self).update()
		if self._should_show_track_level:
			self._can_show_track_level = self.is_enabled()
		else:
			self._can_show_track_level = False
		self._update_track_levels()

	def _update_track_levels(self):
		if not self._should_show_track_level:
			return
		
		for strip in self._channel_strips:
			strip.update_mute_button_color()
		
		if self._can_show_track_level:
			self.canonical_parent.schedule_message(1, self._update_track_levels)
	
	def set_managed_duplicate_button(self, _):
		for strip in self._channel_strips:
			strip.set_duplicate_button(_)

	def set_managed_delete_button(self, _):
		for strip in self._channel_strips:
			strip.set_delete_button(_)
	
	def set_track_select_buttons(self, buttons):
		for strip, button in zip_longest(self._channel_strips, buttons or []):
			if strip:
				strip.set_select_button(button)
