module JamRuby
  class Track < ActiveRecord::Base

    self.table_name = "tracks"

    self.primary_key = 'id'

    default_scope order('created_at ASC')

    SOUND = %w(mono stereo)
  
    belongs_to :connection, :class_name => "JamRuby::Connection", :inverse_of => :tracks
    belongs_to :instrument, :class_name => "JamRuby::Instrument", :inverse_of => :tracks

    validates :sound, :inclusion => {:in => SOUND}

    def self.index(current_user, music_session_id)
      query = Track
        .joins(
          %Q{
            INNER JOIN
              connections
            ON
              connections.music_session_id = '#{music_session_id}'
            AND
              connections.id = connection_id
            AND
              connections.user_id = '#{current_user.id}'
            INNER JOIN
              music_sessions
            ON
              music_sessions.id = '#{music_session_id}'
            AND
              music_sessions.user_id = '#{current_user.id}'
          }
        )

      return query
    end

    def self.save(id, connection_id, instrument_id, sound)
      if id.nil?
        track = Track.new()
        track.connection_id = connection_id
      else
        track = Track.find(id)
      end

      unless instrument_id.nil?
        track.instrument_id = instrument_id
      end

      unless sound.nil?
        track.sound = sound
      end

      track.updated_at = Time.now.getutc
      track.save
      return track
    end
  end
end