from ableton.v2.control_surface.elements import Color as ColorBase
from ableton.v2.base import EventObject, listenable_property, listens

from .colors import color_value

class FX:
	"The possible effects that can be applied to an Exquis color"

	@staticmethod
	def darker(percent):
		"Makes a color darker by a certain percentage"
		return int(percent / 100.0 * 0x3D)
	
	@staticmethod
	def lighter(percent):
		"Makes a color lighter by a certain percentage"
		return int(percent / 100.0 * 0x3D) | 0b01000000
	
	"Flashes the color in accordance with the current tempo"
	pulsate = 0x3F

	"Flashes the color in white in accordance with the current tempo"
	pulsate_white = 0x7F

	"Flashes the color in red in accordance with the current tempo"
	pulsate_red = 0x3E

	"Flashes the color in green in accordance with the current tempo"
	pulsate_green = 0x7E

class Color(ColorBase):
	"A color that can be sent to the Exquis, composed of a palette index and an effect"

	def __init__(self, palette_index, fx=0, *a, **k):
		super(Color, self).__init__(*a, **k)
		self.palette_index = palette_index
		self.fx = fx
	
	def draw(self, interface):
		interface.send_midi((0xBF, interface.message_identifier(), self.palette_index))
		interface.send_midi((0xAF, interface.message_identifier(), self.fx))

class SelectedTrackColor(Color, EventObject):
	"A special color that is always the color of the selected track"

	palette_index = listenable_property.managed(3)
	fx = listenable_property.managed(0)

	def __init__(self, song_view=None, fx=0, offset=0, track_provider=None, *a, **k):
		super(SelectedTrackColor, self).__init__(palette_index=3, fx=fx, *a, **k)
		self.offset = offset
		self.song_view = song_view
		self.track_provider = track_provider
		self.__on_color_changed.subject = song_view
		self.__on_selected_track_changed.subject = song_view
		self.__on_color_changed()

	@listens('selected_track.color')
	def __on_color_changed(self, *a):
		track = self.song_view.selected_track
		song = self.song_view.canonical_parent
		if track not in song.tracks:
			return
		
		if self.offset != 0 and self.track_provider:
			tracks = self.track_provider.tracks_to_use()
			index = tracks.index(track)
			index += self.offset
			if index < 0:
				index = 0
			elif index >= len(tracks):
				index = len(tracks) - 1
			track = tracks[index]

		color_rgb = track.color
		self.palette_index = color_value(color_rgb)

	@listens('selected_track')
	def __on_selected_track_changed(self, *a):
		self.__on_color_changed()
