if Rails.env.development?
  Rails.logger = Logger.new(STDOUT)
end


require 'factory_girl'
require 'open-uri'
#require './spec/factories.rb' # useful when run on a server

namespace :db do
  desc "Add a simple one track recording to the database"
  task single_recording: :environment do
    User.where(:musician => true).order('RANDOM()').limit(10).each do |uu|
      @user = uu
      next if @user.connections.present?
      @connection = FactoryGirl.create(:connection, :user => @user)
      @track = FactoryGirl.create(:track, :connection => @connection, :instrument => Instrument.find('violin'), :client_track_id => "t1")
      @music_session = FactoryGirl.create(:active_music_session, :creator => @user, :musician_access => true)
      @music_session.connections << @connection
      @music_session.save
      @recording = FactoryGirl.create(:recording, :music_session => @music_session, :owner => @user, :id => "R#{rand(10000)}")
      @recorded_track = RecordedTrack.create_from_track(@track, @recording)
      @recorded_track.save
      #@recording = Recording.start(@music_session, @user)
      @recording.stop
      @recording.reload
      @genre = Genre.find('ambient')
      @recording.claim(@user, "name", "description", @genre, true)
      @recording.reload
      @claimed_recording = @recording.claimed_recordings.first
    end
  end

  task clean: :environment do
    DatabaseCleaner.strategy = :truncation, {:except => %w[instruments genres users]}
    DatabaseCleaner.clean_with(:truncation, {:except => %w[instruments genres users]})
    DatabaseCleaner.start
    DatabaseCleaner.clean
  end

  task populate: :environment do
    make_users(30) if 14 > User.count
    make_friends
    make_followings
    make_bands
    make_band_members
    # make_music_sessions_history
    # make_music_sessions_user_history
    make_recording
  end

  task populate_friends: :environment do
    make_friends
  end

  task populate_bands: :environment do
    make_bands
  end

  task populate_band_members: :environment do
    make_band_members
  end

  task populate_band_genres: :environment do
    make_band_genres
  end

  task populate_claimed_recording: :environment do
    make_recording
  end

  task populate_reviews: :environment do
    Teacher.all.each do |teacher|
      @review = Review.new
      @review.target_id = teacher.id
      @review.user = User.last
      @review.rating = 5
      @review.description = 'Omg This teacher was so good.  It was like whoa. Crazy whoa.'
      @review.target_type = 'JamRuby::Teacher'
      @review.save
    end
  end

  task populate_jam_track_genres: :environment do
    genres = Genre.all
    genres = genres.sample(genres.count * 0.75)
    JamTrack.all.each do |jt|
      rand(1..4).downto(1) do |nn|
        gjt = GenreJamTrack.new
        gjt.genre_id = genres.sample.id
        gjt.jam_track_id = jt.id
        gjt.save
      end
    end
  end


  # invoke like:
  # email=seth@jamkazam.com bundle exec rake db:populate_jam_track

  task populate_jam_track: :environment do

    email = ENV['email']
    user = User.find_by_email!(email)

    make_jam_track(user)
  end

  # takes command line args: http://davidlesches.com/blog/passing-arguments-to-a-rails-rake-task
  task :populate_conversation, [:target_email] => :environment do |task, args|
    populate_conversation(args.target_email)
  end

  desc "Fill database with music session sample data"
  task populate_music_sessions: :environment do
    make_users(10) if 14 > User.count
    make_bands if 0==Band.count
    make_music_sessions_history
    make_music_sessions_user_history
  end

  task affiliate_traffic_earnings: :environment do
    partner = FactoryGirl.create(:affiliate_partner)
    user_partner = FactoryGirl.create(:user, affiliate_partner: partner)

    puts "USER CREATED: u: #{user_partner.email}/p: foobar"

    today = Date.today
    quarter1 = FactoryGirl.create(:affiliate_quarterly_payment, affiliate_partner: partner, due_amount_in_cents: 10000, closed:true)
    month1 = FactoryGirl.create(:affiliate_monthly_payment, affiliate_partner: partner, due_amount_in_cents: 10000, closed:true)
  end
end

def make_music_sessions_history
  users = User.all.map(&:id)
  bands = Band.all.map(&:id)
  genres = Genre.all
  20.times do |nn|
    obj = MusicSession.new
    obj.music_session_id = rand(100000000).to_s
    obj.description = 'description goes here'  # Faker::Lorem.paragraph avoid accidental profanity
    obj.user_id = users[rand(users.count)]
    obj.band_id = bands[rand(bands.count)]
    obj.created_at = Time.now - rand(1.month.seconds)
    obj.session_removed_at = obj.created_at + (rand(3)+1).hour
    obj.genre = genres.sample
    obj.legal_terms = true
    obj.name = Faker::Lorem.sentence
    obj.save!
  end
end

def make_music_sessions_user_history
  users = User.all.map(&:id)
  hists = MusicSession.all
  hists.each do |msh|
    (rand(9)+1).times do |nn|
      obj = MusicSessionUserHistory.new
      obj.music_session_id = msh.music_session_id
      obj.user_id = users[rand(users.count)]
      obj.created_at = msh.created_at
      obj.session_removed_at = obj.created_at + (rand(3)+1).hour
      obj.client_id = rand(100000000).to_s
      obj.save!
    end
  end
end

def make_band_members
  Band.find_each do |bb|
    User.order('RANDOM()').limit(4).each do |uu|
      BandMusician.create({:user_id => uu.id, :band_id => bb.id})
    end
  end
end

def make_band_genres
  Band.find_each do |bb|
    next if bb.genres.present?
    Genre.order('RANDOM()').limit(rand(3)+1).each do |gg|
      bb.genres << gg
    end
  end
end

def make_bands
  10.times do |nn|
    name = Faker::Name.name
    website = Faker::Internet.url
    biography = Faker::Lorem.sentence
    city = 'Austin' # Faker::Address.city
    state = 'TX' # Faker::Address.state_abbr
    country = 'US'

    bb = Band.new(
        name: name,
        website: website,
        biography: biography,
        city: city,
        state: state,
        country: country,
    )

    Genre.order('RANDOM()').limit(rand(3)+1).each do |gg|
      bb.genres << gg
    end

    begin
      bb.save!
    rescue
      puts $!.to_s + ' ' + bb.errors.inspect
    end

  end
end

def make_users(num=99)
  admin = User.create!(first_name: Faker::Name.name,
                       last_name: Faker::Name.name,
                       email: Faker::Internet.safe_email,
                       password: "foobar",
                       password_confirmation: "foobar",
                       terms_of_service: true)
  admin.toggle!(:admin)

  instruments = Instrument.all
  genres = Genre.all
  num.times do |n|
    password = "password"
    uu = User.create!(first_name: Faker::Name.name,
                 last_name: Faker::Name.name,
                 terms_of_service: true,
                 email: Faker::Internet.email,
                 password: password,
                 city: Faker::Address.city,
                 state: Faker::Address.state_abbr,
                 country: 'US',
                 password_confirmation: password)
    uu.musician = true
    uu.birth_date = Time.now - 13.years - rand(65).years
    num_instrument = rand(4) + 1
    user_instruments = instruments.sample(num_instrument)
    num_instrument.times do |mm|
      musician_instrument = MusicianInstrument.new
      musician_instrument.player = uu
      musician_instrument.instrument = user_instruments[mm]
      musician_instrument.proficiency_level = rand(3) + 1
      musician_instrument.priority = rand(num_instrument)
      uu.musician_instruments << musician_instrument
    end
    num_genre = rand(4) + 1
    user_genres = genres.sample(num_genre)
    num_genre.times do |mm|
      genre_player = GenrePlayer.new
      genre_player.player_id = uu.id
      genre_player.player_type = uu.class.name
      genre_player.genre_id = user_genres[mm].id
      genre_player.genre_type = GenrePlayer::PROFILE
      uu.genre_players << genre_player
    end
    uu.skill_level = rand(2) + 1
    uu.studio_session_count = rand(100)
    uu.concert_count = rand(40)
    uu.virtual_band = 0==rand(2)
    uu.traditional_band = 0==rand(2)
    uu.paid_sessions = 0==rand(2)
    uu.free_sessions = 0==rand(2)
    uu.cowriting = 0==rand(2)
    uu.save!
    yn = true
    while yn
      begin
        uu.biography = Faker::Lorem.sentence
        uu.save!
        yn = false
      rescue
      end
    end
  end
end

def make_microposts
  users = User.all(limit: 6)
  50.times do
    content = Faker::Lorem.sentence(5)
    users.each { |user| user.microposts.create!(content: content) }
  end
end

def make_relationships
  users = User.all
  user = users.first
  followed_users = users[2..50]
  followers = users[3..40]
  followed_users.each { |followed| user.followings << followed }
  followers.each { |follower| follower.follow!(user) }
end

def make_followings
  users = User.all
  users.each do |uu|
    users[0..rand(users.count)].shuffle.each do |uuu|
      next if 0 < Follow.where(:followable_id => uu.id, :user_id => uuu.id).count
      follow = Follow.new
      follow.followable = uu
      follow.user = uuu
      follow.save
    end
  end
end

def make_friends
  users = User.all
  users[6..-1].each do |uu|
    users[0..5].shuffle.each do |uuu|
      Friendship.save(uu.id, uuu.id)
    end
  end
end

def make_recorded_track(recording, user, instrument, md5, length, filename)
  recorded_track = RecordedTrack.new
  recorded_track.user = user
  recorded_track.instrument = Instrument.find(instrument)
  recorded_track.sound = 'stereo'
  recorded_track.client_id = user.id
  recorded_track.client_track_id = SecureRandom.uuid
  recorded_track.track_id = SecureRandom.uuid
  recorded_track.md5 = md5
  recorded_track.length = length
  recorded_track[:url] = filename
  recorded_track.fully_uploaded = true
  recorded_track.is_skip_mount_uploader = true
  recording.recorded_tracks << recorded_track
end

def make_claimed_recording(recording, user, name, description)
  claimed_recording = ClaimedRecording.new
  claimed_recording.user = user
  claimed_recording.name = name
  claimed_recording.description = description
  claimed_recording.is_public = true
  claimed_recording.genre = Genre.first
  recording.claimed_recordings << claimed_recording
end


def make_recording
  # need 4 users.
  users = User.where(musician: true).limit(4)
  raise "need at least 4 musicians in the database to create a recording" if users.length < 4

  user1 = users[0]
  user2 = users[1]
  user3 = users[2]
  user4 = users[3]

  recording = Recording.new
  recording.name = 'sample data'
  recording.owner = user1

  make_recorded_track(recording, user1, 'bass guitar', 'f86949abc213a3ccdc9d266a2ee56453', 2579467, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-adrian-bass.ogg')
  make_recorded_track(recording, user1, 'voice', '264cf4e0bf14d44109322a504d2e6d18', 2373055, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-adrian-vox.ogg')
  make_recorded_track(recording, user2, 'electric guitar', '9f322e1991b8c04b00dc9055d6be933c', 2297867, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-chris-guitar.ogg')
  make_recorded_track(recording, user2, 'voice', '3c7dcb7c4c35c0bb313fc15ee3e6bfd5', 2244968, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-chris-vox.ogg')
  make_recorded_track(recording, user3, 'voice', '10ca4c6ef5b98b3489ae8da1c7fa9cfb', 2254275, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-matt-lead-vox.ogg')
  make_recorded_track(recording, user4, 'drums', 'ea366f482fa969e1fd8530c13cb75716', 2386250, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-randy-drum1.ogg')
  make_recorded_track(recording, user4, 'drums', '4c693c6e99117719c6340eb68b0fe574', 2566463, 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/track-randy-drum2.ogg')

  make_claimed_recording(recording, user1, 'Poison', 'Classic song that you all know -- user1')
  make_claimed_recording(recording, user2, 'Poison', 'Classic song that you all know -- user2')
  make_claimed_recording(recording, user3, 'Poison', 'Classic song that you all know -- user3')
  make_claimed_recording(recording, user4, 'Poison', 'Classic song that you all know -- user4')

  mix = Mix.new
  mix.started_at = Time.now
  mix.completed_at = Time.now
  mix[:ogg_url] = 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/master-out.ogg'
  mix.ogg_md5 = 'f1fee708264602e1705638e53f0ea667'
  mix.ogg_length = 2500633
  mix[:mp3_url] = 'https://jamjam:blueberryjam@int.jamkazam.com/stuff/lc_rocks_poison/master-out.mp3'
  mix.mp3_md5 = 'df05abad96e5cb8439f7cd6e31b5c503'
  mix.mp3_length = 3666137
  mix.completed = true
  recording.mixes << mix
  recording.save!(validate: false)
end

def make_jam_track(user)

  number = 0

  JamTrack.transaction do

    track = JamTrack.where('name like ?', 'bootstrapped-%').order('name DESC').first
    if track
      puts "found existing JamTrack with name #{track.name}"
      index = track.name.index('-')
      number = track.name[index+1..-1].to_i + 1 # increment most recent bootstrapped by 1
    end

    suffix = number.to_s.rjust(3, '0') # 0 pad a bit

    new_name ='bootstrapped-' + suffix

    puts "creating jam_track with name #{new_name}"

    licensor = JamTrackLicensor.first
    if licensor
      jam_track = FactoryGirl.create(:jam_track, name: new_name, licensor: licensor)
    else
      jam_track = FactoryGirl.create(:jam_track, name: new_name)
    end


    jam_track_track = jam_track.jam_track_tracks[0]

    download_filename = Dir::Tmpname.make_tmpname(["#{Dir.tmpdir}/bootstrapped-" + suffix, '.ogg'], nil)

    puts "downloading ogg file from int.jamkazam.com"
    File.open(download_filename, "wb") do |saved_file|
      open("https://int.jamkazam.com/stuff/lc_rocks_poison/track-adrian-vox.ogg", "rb", {http_basic_authentication: ["jamjam", "blueberryjam"]}) do |read_file|
        saved_file.write(read_file.read)
      end
    end

    puts "uploading ogg file to s3"
    # let's put in a real ogg file into S3, so that the JamTracksBuilder job can succeed
    s3_manager = S3Manager.new(APP_CONFIG.aws_bucket, APP_CONFIG.aws_access_key_id, APP_CONFIG.aws_secret_access_key)
    url = jam_track_track.store_dir + "/" + jam_track_track.filename
    s3_manager.upload(url, download_filename)
    jam_track_track[:url] = url
    jam_track_track.length = File.size(download_filename)
    jam_track_track.md5 = '264cf4e0bf14d44109322a504d2e6d18'
    jam_track_track.save!

    puts "'purchasing' jamtrack for user #{user.email}"
    right = FactoryGirl.create(:jam_track_right, user: user, jam_track: jam_track)

    puts "creating .jkz file"
    JamTracksBuilder.perform(right.id)

    puts "------------------------------------"
    puts "------------------------------------"
    puts "---- SAVING JKZ AND PEM TO DISK ----"
    puts "------------------------------------"
    puts "------------------------------------"

    right.reload

    jkz_outfile = "tmp/#{jam_track.id}.jkz"
    jkz_private_key = "tmp/#{jam_track.id}.pem"

    File.open(jkz_private_key, 'w') {|f| f.write(right.private_key) }
    s3_manager.download(right[:url], jkz_outfile)

    puts "------------------------------------"
    puts "------------------------------------"
    puts "JKZ PACKAGE:     #{jkz_outfile}"
    puts "JKZ PRIVATE KEY: #{jkz_private_key}"
    puts "------------------------------------"
    puts "------------------------------------"


  end

end

def populate_conversation(target_email)
  all_users = User.all

  target_users = target_email ? User.where(email: target_email) : all_users

  target_users.each do |target_user|
    all_users.each do |other_user|
      next if target_user == other_user
      20.times do
        FactoryGirl.create(:notification_text_message, target_user: target_user, source_user: other_user, message: Faker::Lorem.characters(rand(400)))
      end
    end
  end
end