ActiveAdmin.register  JamRuby::FraudAlert, :as => 'Fraud Alerts' do

  menu :label => 'Fraud Alerts', :parent => 'JamTracks'

  config.sort_order = 'created_at desc'
  config.batch_actions = false


  scope("Not Whitelisted", default:true) { |scope|
    scope.joins('INNER JOIN "machine_fingerprints" ON "machine_fingerprints"."id" = "fraud_alerts"."machine_fingerprint_id" LEFT OUTER JOIN "fingerprint_whitelists" ON "fingerprint_whitelists"."fingerprint" = "machine_fingerprints"."fingerprint"').where('fingerprint_whitelists IS NULL')}

  index do
    actions

    column :machine_fingerprint
    column :user
    column :created_at
    column :resolved

    column "" do |alert|
      link_to 'Matching MAC', "fraud_alerts/#{alert.id}/same_fingerprints"
    end
    column "" do |alert|
      link_to 'Matching MAC and IP Address', "fraud_alerts/#{alert.id}/same_fingerprints_and_ip"
    end
    column "" do |alert|
      link_to 'Matching IP Address', "fraud_alerts/#{alert.id}/same_ip"
    end
    column "" do |alert|
      link_to 'Resolve', "fraud_alerts/#{alert.id}/resolve"
    end
    column "" do |alert|
      link_to 'Whitelist Similar', "fraud_alerts/#{alert.id}/whitelist"
    end
  end

  member_action :same_fingerprints, :method => :get do
    alert = FraudAlert.find(params[:id])

    redirect_to admin_machine_fingerprints_path("q[fingerprint_equals]" => alert.machine_fingerprint.fingerprint, commit: 'Filter', order: 'created_at_desc')
  end

  member_action :same_fingerprints_and_ip, :method => :get do
    alert = FraudAlert.find(params[:id])

    redirect_to admin_machine_fingerprints_path("q[fingerprint_equals]" => alert.machine_fingerprint.fingerprint, "q[remote_ip_equals]" => alert.machine_fingerprint.remote_ip, commit: 'Filter', order: 'created_at_desc')
  end


  member_action :resolve, :method => :get do
    alert = FraudAlert.find(params[:id])
    alert.resolved = true
    alert.save!

    redirect_to admin_fraud_alerts_path, notice: "That fraud alert has been marked as resolved"
  end

  member_action :whitelist, :method => :get do
    alert = FraudAlert.find(params[:id])

    wl = FingerprintWhitelist.new
    wl.fingerprint = alert.machine_fingerprint.fingerprint
    success = wl.save

    redirect_to admin_fraud_alerts_path, notice: success ? "Added #{alert.machine_fingerprint.fingerprint} to whitelist" : "Could not add #{alert.machine_fingerprint.fingerprint} to whiteliste"
  end


end