module JamRuby
  class JamTrackTapIn < ActiveRecord::Base

    attr_accessible :jam_track_id, :offset_time, :offset_time_raw, :bpm, :tap_in_count, as: :admin

    validates :offset_time,  presence: true, numericality: {only_integer: true}, length: {in: 1..1000}
    validates :jam_track,  presence: true
    validates :bpm, presence: true
    validates_format_of :bpm,   with: /^\d+\.*\d{0,1}$/
    validates :tap_in_count,    presence: true, numericality: {only_integer: true}

    belongs_to :jam_track, class_name: "JamRuby::JamTrack"

    # this is used by active admin/jam-admin
    def offset_time_raw
      if self.offset_time.nil? || self.offset_time.nil?
        '00:00:000'
      else
        seconds = self.offset_time.to_f/1000
        time = Time.at(seconds)
        time.strftime("%M:%S:#{(self.offset_time % 1000).to_s.rjust(3, '0')}")
      end
    end

    # this is used by active admin/jam-admin
    def offset_time_raw=(new_value)
      if new_value && new_value.kind_of?(String) && new_value.include?(':')
        bits = new_value.split(':')
        if bits.length != 3
          raise "format of offset time must be MM:SS:MLS"
        end

        self.offset_time = (bits[0].to_i * 60000) + (bits[1].to_i * 1000) + (bits[2].to_i)

      else
        raise "format of offset time must be MM:SS:MLS"
      end
    end
  end
end