module AdCampaignsHelper
  def self.spacer(val, total)
    percentage = ((val * 100) / total.to_f).round(1).to_s
    ('%-5.5s' % percentage).gsub(' ', '&nbsp;') + '%&nbsp;-&nbsp;' + val.to_s
  end

  def self.cac(campaign)
    if campaign.subscribed && campaign.subscribed > 0
      (campaign.spend/campaign.subscribed.to_f).round(2) 
    end
  end

  def self.cac_divide_by_ltv(campaign)
    customer_ltv = GenericState.singleton.customer_ltv
    if cac(campaign) && customer_ltv && customer_ltv > 0
      return (cac(campaign)/customer_ltv.to_f).round(2)
    end
  end

  def self.format_number(num)
    if num
      num.to_s.reverse.scan(/\d{3}|.+/).join(",").reverse
    end
  end

end


ActiveAdmin.register JamRuby::AdCampaign, as: 'AdCampaign' do
  menu :label => 'Ad Campaigns', :parent => 'Reports'
  before_filter :skip_sidebar!, :only => :index
  config.batch_actions = false
  config.clear_action_items!
  config.sort_order = "users.origin_utm_campaign DESC"
  config.per_page = 100
  config.paginate = true


  index do
    div do
      render 'customer_ltv'
    end
    
    column "Campaign" do |campaign|
      campaign.origin_utm_campaign
    end
    column "Medium" do |campaign|
      campaign.origin_utm_medium
    end
    column "End Date" do |campaign|
      best_in_place campaign, :end_date, as: :date, url: inplace_update_admin_ad_campaigns_path(campaign: campaign.origin_utm_campaign, medium: campaign.origin_utm_medium), param: 'ad_campaign', classes: 'ac_bip'
    end
    column "Hard Date" do |campaign|
      (campaign.end_date + 45.days).strftime('%Y-%m-%d') if campaign.end_date.present?
    end
    column "Subscribed" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.subscribed, campaign.joined))
    end
    column "Spend" do |campaign|
      best_in_place campaign, :spend, as: :input, url: inplace_update_admin_ad_campaigns_path(campaign: campaign.origin_utm_campaign, medium: campaign.origin_utm_medium), param: 'ad_campaign', display_with: Proc.new{|spend| number_to_currency(spend) }, classes: 'ac_bip'
    end
    column "CAC" do |campaign|
      number_to_currency(AdCampaignsHelper.cac(campaign)) if AdCampaignsHelper.cac(campaign) && AdCampaignsHelper.cac(campaign) > 0    
    end
    column "LTV/CAC" do |campaign|
      AdCampaignsHelper.cac_divide_by_ltv(campaign)
    end
    column "Referred" do |campaign|
      best_in_place campaign, :referred, as: :input, url: inplace_update_admin_ad_campaigns_path(campaign: campaign.origin_utm_campaign, medium: campaign.origin_utm_medium), param: 'ad_campaign', display_with: Proc.new{|referred| AdCampaignsHelper.format_number(referred) }, classes: 'ac_bip'
    end
    column "Signed Up" do |campaign|
      if campaign.referred && campaign.referred > 0
        raw(AdCampaignsHelper.spacer(campaign.joined, campaign.referred))
      else
        raw("? - #{campaign.joined}")
      end
    end
    column "Downloaded" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.downloaded, campaign.joined))
    end
    column "Ran Client" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.ran_client, campaign.joined))
    end
    column "FTUE" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.ftue, campaign.joined))
    end
    column "Any Session" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.any_session, campaign.joined))
    end
    column "2+ Session" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.real_session, campaign.joined))
    end
    column "Good Session" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.good_session, campaign.joined))
    end
    column "Invited" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.invited, campaign.joined))
    end
    column "Friended" do |campaign|
      raw(AdCampaignsHelper.spacer(campaign.friended, campaign.joined))
    end
    column "Platinum" do |campaign|
      campaign.platinum
    end
    column "Gold" do |campaign|
      campaign.gold
    end
    column "Silver" do |campaign|
      campaign.silver
    end
    
  end

  controller do
    def scoped_collection
      User.select("users.origin_utm_campaign, 
        users.origin_utm_medium, COUNT(users.id) AS joined, 
        COUNT(users.first_downloaded_client_at) AS downloaded, 
        COUNT(users.first_subscribed_at) AS subscribed,
        COUNT(users.first_ran_client_at) AS ran_client,
        COUNT(users.first_certified_gear_at) AS ftue,
        COUNT(users.first_music_session_at) AS any_session,
        COUNT(users.first_real_music_session_at) AS real_session,
        COUNT(users.first_good_music_session_at) AS good_session,
        COUNT(users.first_invited_at) AS invited,
        COUNT(users.first_friended_at) AS friended,
        COUNT(CASE WHEN users.first_subscribed_plan_code = 'jamsubplatinum' OR users.first_subscribed_plan_code = 'jamsubplatinumyearly' THEN users.first_subscribed_plan_code END) AS platinum,
        COUNT(CASE WHEN users.first_subscribed_plan_code = 'jamsubgold' OR users.first_subscribed_plan_code = 'jamsubgoldyearly' THEN users.first_subscribed_plan_code END) AS gold,
        COUNT(CASE WHEN users.first_subscribed_plan_code = 'jamsubsilver' OR users.first_subscribed_plan_code = 'jamsubsilveryearly' THEN users.first_subscribed_plan_code END) AS silver,
        ad_campaigns.id,
        COALESCE(MAX(ad_campaigns.referred), NULL) as referred, 
        COALESCE(MAX(ad_campaigns.end_date), NULL) AS end_date, 
        COALESCE(MAX(ad_campaigns.spend), 0) AS spend").joins("
        LEFT JOIN ad_campaigns ON users.origin_utm_campaign = ad_campaigns.campaign 
        AND users.origin_utm_medium = ad_campaigns.medium").where("
        users.origin_utm_campaign IS NOT NULL AND users.origin_utm_medium IS NOT NULL AND users.origin_utm_source = 'paid'").group("
        ad_campaigns.id, users.origin_utm_campaign, users.origin_utm_medium").order("
        users.origin_utm_campaign DESC")
    end


    def permitted_params
      params.permit :campaign, :medium, :_method, ad_campaign: [:spend, :referred, :end_date]
    end
  end

  collection_action :inplace_update, method: :put do
    campaign = permitted_params[:campaign]
    medium = permitted_params[:medium]
    @ad_campaign = JamRuby::AdCampaign.where(campaign: campaign, medium: medium).first_or_create
    respond_to do |format|
      if @ad_campaign.update_attributes(permitted_params[:ad_campaign])
        format.json {  head :ok }
      else
        format.json{ render :json => @ad_campaign.errors.full_messages, :status => :unprocessable_entity }
      end
    end
  end

  
end
