namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    make_users
    make_microposts
    make_relationships
  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
end

def make_music_sessions_history
    users = User.all.map(&:id)
    bands = Band.all.map(&:id)
    genres = Genre.all.map(&:description)
    50.times do |nn|
      obj = MusicSessionHistory.new
      obj.music_session_id = rand(100000000).to_s
      obj.description = Faker::Lorem.paragraph
      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.genres = genres.shuffle[0..rand(4)].join(' | ')
      obj.save!
    end     
end

def make_music_sessions_user_history
    users = User.all.map(&:id)
    hists = MusicSessionHistory.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_bands
    10.times do |nn|
      name = Faker::Name.name
      website = Faker::Internet.url
      biography = Faker::Lorem.sentence
      city = Faker::Address.city      
      state = Faker::Address.state_abbr
      country = Faker::Address.country

      Band.create!(
        name: name,
        website: website,
	biography: biography,
	city: city,
	state: state,
	country: country,
      )

    end 
end	

def make_users(num=99)
  admin = User.create!( first_name: Faker::Name.name,
  	  		last_name: Faker::Name.name,
			email:    "example@railstutorial.org",
                       password: "foobar",
                       password_confirmation: "foobar",
		       terms_of_service: true)
  admin.toggle!(:admin)
  num.times do |n|
    email = "example-#{n+1}@railstutorial.org"
    password  = "password"
    User.create!(first_name: Faker::Name.name,
  	  		last_name: Faker::Name.name,
			terms_of_service: true,
			email:    email,
                 password: password,
                 password_confirmation: password)
  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.follow!(followed) }
  followers.each      { |follower| follower.follow!(user) }
end