namespace :jam_tracks do

  task dry_run: :environment do |task, args|
    JamTrackImporter.dry_run
  end

  task sync: :environment do |task, args|
    path = ENV['TRACK_PATH']

    if !path
      puts "TRACK_PATH must be set to something like AD DC/Back in Black"
      exit(1)
    end

    JamTrackImporter.synchronize_from_meta("audio/#{path}/meta.yml", skip_audio_upload:false)
  end

  task resync_audio: :environment do |task, args|
    path = ENV['TRACK_PATH']

    if !path
      puts "TRACK_PATH must be set to something like AD DC/Back in Black"
      exit(1)
    end

    JamTrackImporter.synchronize_from_meta("audio/#{path}/meta.yml", resync_audio:true, skip_audio_upload:false)
  end

  task sync_all: :environment do |task, args|
    JamTrackImporter.synchronize_all(skip_audio_upload:false)
  end

  task sync_all_dev: :environment do |task, args|
    JamTrackImporter.synchronize_all(skip_audio_upload:true)
  end

  task sync_previews_all: :environment do |task, arg|
    JamTrackImporter.synchronize_previews
  end

  task sync_master_preview_all: :environment do |task, args|
    importer = JamTrackImporter.synchronize_jamtrack_master_previews
  end

  # syncs just one master track for a give JamTrack
  task sync_master_preview: :environment do |task, args|
    plan_code = ENV['PLAN_CODE']
    if !plan_code
      puts "PLAN_CODE must be set to something like jamtrack-acdc-backinblack"
      exit(1)
    end

    jam_track = JamTrack.find_by_plan_code!(plan_code)

    importer = JamTrackImporter.synchronize_jamtrack_master_preview(jam_track)

    if importer.reason.nil? || importer.reason == "success" || importer.reason == "jam_track_exists"
      puts("#{importer.name} #{importer.reason}")
    else
      puts("#{importer.name} failed to import.")
      puts("#{importer.name} reason=#{importer.reason}")
      puts("#{importer.name} detail=#{importer.detail}")
    end
  end

  task sync_duration_all: :environment do |task, args|
    importer = JamTrackImporter.synchronize_durations
  end

  # syncs just one master track for a give JamTrack
  task sync_duration: :environment do |task, args|
    plan_code = ENV['PLAN_CODE']
    if !plan_code
      puts "PLAN_CODE must be set to something like jamtrack-acdc-backinblack"
      exit(1)
    end

    jam_track = JamTrack.find_by_plan_code!(plan_code)

    importer = JamTrackImporter.synchronize_duration(jam_track)

    if importer.reason.nil? || importer.reason == "success" || importer.reason == "jam_track_exists"
      puts("#{importer.name} #{importer.reason}")
    else
      puts("#{importer.name} failed to import.")
      puts("#{importer.name} reason=#{importer.reason}")
      puts("#{importer.name} detail=#{importer.detail}")
    end
  end

  task download_masters: :environment do |task, arg|
    JamTrackImporter.download_masters
  end
end
