ActiveAdmin.register_page "Fake Purchaser"  do
  menu :parent => 'Misc'


  page_action :bulk_jamtrack_purchase, :method => :post do

    user_field = params[:jam_ruby_jam_track_right][:user]

    if user_field.blank?
      redirect_to admin_fake_purchaser_path, :notice => "user not specified"
      return
    end

    bits = user_field.strip.split(' ')

    user = User.find_by_email(bits[0])
    if user.nil?
      redirect_to admin_fake_purchaser_path, :notice =>"no user with email #{bits[0]}"
      return
    end

    if !user.admin
      redirect_to admin_fake_purchaser_path, :notice =>"user is not admin"
      return
    end

    count = 0
    JamTrack.all.each do |jam_track|
      unless jam_track.right_for_user(user)
        jam_track_right=JamTrackRight.new
        jam_track_right.user = user
        jam_track_right.jam_track = jam_track
        jam_track_right.is_test_purchase = true
        jam_track_right.version = jam_track.version
        jam_track_right.can_download = true
        jam_track_right.save!
        count = count + 1
      end
    end

    redirect_to admin_fake_purchaser_path, :notice => "Bought #{count} jamtracks for #{user.email}"
  end

  content do
    active_admin_form_for JamTrackRight.new, :url => admin_fake_purchaser_bulk_jamtrack_purchase_path, :builder => ActiveAdmin::FormBuilder do |f|
        inputs "Admin User to Fake JamTrack Purchases" do
          input :user, :as => :autocomplete, :url => autocomplete_user_email_admin_users_path, :input_html => { :id_element => "#jam_trak_right_user_id" }, hint: 'All JamTracks in the system will be \'bought\' for this user. No Recurly interaction occurs with this feature.'
        end
        actions
      end
  end
end
