from ableton.v2.base import listens
from ableton.v2.control_surface.component import Component
from ableton.v2.control_surface.control import ToggleButtonControl

from ..color import SelectedTrackColor, FX

class TransportComponent(Component):
	"A component that handles the transport controls of the Exquis"
	
	start_stop = ToggleButtonControl(toggled_color="Transport.PlayOn", untoggled_color="Transport.PlayOff")
	record = ToggleButtonControl(toggled_color="Transport.RecOn", untoggled_color="Transport.RecOff")

	def __init__(self, *a, **k):
		super(TransportComponent, self).__init__(*a, **k)

		self.on_is_playing_changed.subject = self.song

		self.session_mode = False
		self.on_record_mode_changed.subject = self.song
		self.on_session_record_changed.subject = self.song
		self.application.view.add_is_view_visible_listener("Session", self.on_session_visible_changed)
		self.on_session_visible_changed(None)

		color = SelectedTrackColor(self.song.view, FX.darker(100))
		self.start_stop.untoggled_color = color
		self.record.untoggled_color = color

	def disconnect(self):
		self.application.view.remove_is_view_visible_listener("Session", self.on_session_visible_changed)
		super(TransportComponent, self).disconnect()

	@start_stop.pressed
	def on_start_stop_pressed(self, _):
		self.song.is_playing = not self.song.is_playing
	@start_stop.released_delayed
	def on_start_stop_pressed_delayed(self, _):
		self.song.is_playing = False
		self.song.jump_by(-self.song.current_song_time)
		
	@listens("is_playing")
	def on_is_playing_changed(self):
		self.start_stop.is_toggled  = self.song.is_playing

	@record.released_immediately
	def on_record_pressed(self, _):
		if self.session_mode:
			self.song.session_record = not self.song.session_record
		else:
			self.song.record_mode = not self.song.record_mode
	@record.released_delayed
	def on_record_pressed_delayed(self, _):
		if self.session_mode:
			self.song.capture_midi()
		self.update_record()
	
	@listens("record_mode")
	def on_record_mode_changed(self):
		self.update_record()
	
	@listens("session_record")
	def on_session_record_changed(self):
		self.update_record()

	def update_record(self):
		self.record.is_toggled = self.song.session_record if self.session_mode else self.song.record_mode

	def on_session_visible_changed(self, *a):
		self.session_mode = self.application.view.is_view_visible("Session")
		self.update_record()
