ActiveAdmin.register_page "EventBriteOrderUploads" do

  menu :label => 'Event Brite Order Upload', :parent => 'Misc'

  page_action :upload_eventbriteorders, :method => :post do
    EventBriteOrder.transaction do

      puts params


      live_stream = LiveStream.find_by_id!(params[:jam_ruby_event_brite_order][:live_stream_id])

      file = params[:jam_ruby_event_brite_order][:csv]

      upload = EventBriteOrderUpload.new
      upload.upload_file_name = file.original_filename
      upload.save!

      array_of_arrays = CSV.read(file.tempfile.path, headers:true)
      array_of_arrays.each do |row|
        order_id = row['Order ID']

        event_brite_order = EventBriteOrder.find_by_order_id(order_id)
        if event_brite_order.nil?
          event_brite_order = EventBriteOrder.new
        end
        event_brite_order.event_brite_order_upload = upload
        event_brite_order.live_stream = live_stream
        event_brite_order.event_name = row['Event Name']
        event_brite_order.order_id = order_id
        event_brite_order.ticket_count = row['Tickets']
        event_brite_order.ticket_type = row['Type']
        event_brite_order.first_name = row['First Name']
        event_brite_order.last_name = row['Last Name']
        event_brite_order.email = row['Email Address']
        event_brite_order.save!
      end

      redirect_to admin_eventbriteorderuploads_path, :notice => "Created #{array_of_arrays.length} event brite orders!"
    end
  end
  content do
    active_admin_form_for EventBriteOrder.new, :url => admin_eventbriteorderuploads_upload_eventbriteorders_path, :builder => ActiveAdmin::FormBuilder do |f|
      f.inputs "Upload Event Brite Orders" do
        f.input :csv, as: :file, required: true, :label => "An event brite order CSV exactly as exported from Eventbrite"
        f.input :live_stream, required:true, as: :select, :collection => LiveStream.upcoming
      end
      f.actions
    end
  end
end
