class RecordedTrackUploader < CarrierWave::Uploader::Base
  # include CarrierWaveDirect::Uploader
  include CarrierWave::MimeTypes

  process :set_content_type
  process :add_metadata

  def initialize(*)
    super
    JamRuby::UploaderConfiguration.set_aws_private_configuration(self)
  end

  def add_metadata

    # add this metadata to ogg file without disturbing audio
    #JamRecordingId=af9f1598-2243-4c21-98c1-5e0c56da5b89
    #JamTrackId=5b1c3ef4-01d7-471e-8684-e2a5743ffd26
    #JamClientId=8331bcec-7810-42c1-9f39-a5c129406e85
    #JamType=LocalTrack

    # secret sauce is -codec copy (or -acodec), and a bunch of -metadata arguments
    # after done, stomp input file with new one

    input_file = current_path
    output_file = current_path + '.new.ogg'
    codec_param = RUBY_PLATFORM.include?('darwin') ? 'codec' : 'acodec'
    ffmpeg_cmd = "#{APP_CONFIG.ffmpeg_path} -i \"#{input_file}\" -#{codec_param} copy -metadata JamRecordingId=#{model.recording_id} -metadata JamTrackId=#{model.client_track_id} -metadata JamClientId=#{model.client_id} -metadata JamType=LocalTrack \"#{output_file}\""
    system(ffmpeg_cmd)

    unless $? == 0
      raise "ffmpeg failed. cmd: #{ffmpeg_cmd}"
    end

    FileUtils.mv output_file, input_file
  end

  # Add a white list of extensions which are allowed to be uploaded.
  def extension_white_list
    %w(ogg)
  end

  def store_dir
    nil
  end

  def md5
    @md5 ||= ::Digest::MD5.file(current_path).hexdigest
  end

  def filename
    model.filename if model.id
  end
end
