class JamRuby::JamTrackTrack

  # add a custom validation

  validate :preview

  def preview
    if preview_generate_error
      errors.add(:preview_start_time, preview_generate_error)
    end
  end


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

  # this is used by active admin/jam-admin
  def preview_start_time_raw=(new_value)

    value = nil
    if new_value == nil || new_value == ''
      value = nil
    else
      if new_value && new_value.kind_of?(String) && new_value.include?(':')
        bits = new_value.split(':')
        if bits.length != 3
          raise "format of preview start time must be MM:SS:MLS"
        end

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

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

    if !value.nil? && value != self.preview_start_time
      self.preview_start_time = value
      generate_preview
    else
      self.preview_start_time = value
    end
  end

end
