ActiveAdmin.register_page "Giftcarduploads" do

  menu :label => 'Gift Cards Upload', :parent => 'JamTracks'

  page_action :upload_giftcards, :method => :post do
    GiftCard.transaction do

      puts params

      file = params[:jam_ruby_gift_card][:csv]
      array_of_arrays = CSV.read(file.tempfile.path)
      array_of_arrays.each do |row|
        if row.length != 1
          raise "UKNONWN CSV FORMAT!  Must be 1 column"
        end

        code = row[0]

        gift_card = GiftCard.new
        gift_card.code = code
        gift_card.card_type = params[:jam_ruby_gift_card][:card_type]
        gift_card.origin = file .original_filename
        gift_card.save!
      end

      redirect_to admin_giftcarduploads_path, :notice => "Created #{array_of_arrays.length} gift cards!"
    end
  end

  content do
    active_admin_form_for GiftCard.new, :url => admin_giftcarduploads_upload_giftcards_path, :builder => ActiveAdmin::FormBuilder do |f|
        f.inputs "Upload Gift Cards" do
          f.input :csv, as: :file, required: true, :label => "A single column CSV that contains ONE type of gift card (5 JamTrack, 10 JamTrack, etc)"
          f.input :card_type, required:true, as: :select, :collection => JamRuby::GiftCard::CARD_TYPES
        end
        f.actions
      end
    end

end

