module SessionsHelper

  def sign_in(user)
    set_remember_token(user)
    set_jamkazam_user_cookies
    set_purchased_jamtrack_cookie unless user.has_redeemable_jamtrack
    self.current_user = user
  end

  def set_remember_token(user)
    if @session_only_cookie
      cookies.delete(:remember_token)
      cookies[:remember_token] = {
          value: user.remember_token,
          domain: Rails.application.config.session_cookie_domain
      }
    else
      cookies[:remember_token] = {
        value: user.remember_token,
        expires: 20.years.from_now.utc,
        domain: Rails.application.config.session_cookie_domain
      }
    end
  end

  # should be set whenever a user logs in who has  redeemed a free jamtrack, or whenever the user
  def set_purchased_jamtrack_cookie
    cookies.permanent[:redeemed_jamtrack] = true
  end

  def set_jamkazam_user_cookies
    cookies.permanent[:jamkazam_user] = true
  end

  def complete_sign_in(user, redirect=true)
    sign_in user

    # port over any shopping cart items
    if has_anonymous_user?
      shopping_carts = anonymous_user.shopping_carts

      ShoppingCart.move_to_user(user, anonymous_user, shopping_carts)
    end

    if redirect
      if params[:sso] == "desk"
        redirect_to_support_after_signin(user)
      elsif params[:sso] == 'forums'
        redirect_to_forums_after_signin
      else
        redirect_after_signin(client_path)
      end
    end
  end

  def signed_in?
    !current_user.nil?
  end

  def has_anonymous_user?
    !anonymous_user.nil?
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def current_timezone
    @current_timezone ||= cookies[:'browser.timezone'] || any_user.timezone
  end

  def anonymous_user=(anonymous_user)
    @anonymous_user = anonymous_user
  end

  def anonymous_user
    if anon_cookie
      @anonymous_user ||= AnonymousUser.new(anon_cookie, cookies)
    else
      nil
    end
  end

  # tries current_user over anonymous_user
  def any_user
    current_user || anonymous_user
  end

  def anon_cookie
    @anon_cookie ||= cookies[:user_uuid]
  end

  def new_user(user, signup_hint)

    want_jamblaster = false
    redirect_location = nil
    if signup_hint
      want_jamblaster = signup_hint.want_jamblaster
      redirect_location = signup_hint.redirect_location
    end

    cookies[:new_user] = { musician: user.musician, registrationType: user.user_authorization('facebook') ? 'Facebook' : 'Native', want_jamblaster: want_jamblaster, redirect_location: redirect_location }.to_json
  end


  # given the current user, and any signup hint (can be nil)
  # handle the final destination of the user
  def handle_signup_hint(user, signup_hint, default_redirect)
    redirect_url = default_redirect
    if signup_hint
      if signup_hint.want_jamblaster
        User.where(id: user.id).update_all(want_jamblaster: true)
      end

      if signup_hint.redirect_location
        redirect_url = signup_hint.redirect_location
      end
    end

    redirect_url
  end


  def current_user?(user)
    user == current_user
  end

  def signed_in_user
    unless signed_in?
      store_location
      redirect_to signin_url, notice: "Please sign in."
    end
  end

  def transactions_filter
    ActiveRecord::Base.transaction do
      yield
    end
  end

  def api_signed_in_user
    unless signed_in?
      render :json => { :message => "not logged in"}, :status => 403
    end
  end


  def posa_http_basic_auth
    @retailer = Retailer.find_by_slug(params[:slug])

    if @retailer.nil?
      redirect_to signin_url, notice: "Please use the correct url for retailers in."
      return
    end

    authenticate_or_request_with_http_basic('Administration') do |username, password|
      @retailer.matches_password(password)
    end
  end

  def ip_blacklist
    if current_user && current_user.admin
      return
    end

    if @jam_track_right && !@jam_track_right.redeemed
      return
    end

    if IpBlacklist.banned(request.remote_ip) && (current_user && !UserWhitelist.listed(current_user))
      Stats.write('web.blacklist.ip', {value: 1, remote_ip: request.remote_ip})
      render :json => { :message => "IP blacklisted"}, :status => 403
    end
  end

  def user_blacklist
    if current_user && current_user.admin
      return
    end

    if @jam_track_right && !@jam_track_right.redeemed
      return
    end

    # not yet; we can track the thief by not outright banning
    #if EmailBlacklist.banned(current_user)
    #  Stats.write('web.blacklist.user', {value: 1, user_id: current_user.id})
    #  render :json => { :message => "User blacklisted via email"}, :status => 403
    #end

    if UserBlacklist.banned(current_user)
      Stats.write('web.blacklist.user', {value: 1, user_id: current_user.id})
      render :json => { :message => "User blacklisted"}, :status => 403
    end

  end

  # take either the signed in user, or if that fails, try the anonymous user
  def api_any_user
    unless signed_in? || has_anonymous_user?
      render :json => { :message => "not logged in"}, :status => 403
      end
  end

  def api_anonymous_user
    unless has_anonymous_user?
      render :json => { :errors => {:user_uuid => ['not specified']}}, :status => 422
    end

  end
  def sign_out
    current_user = nil
    cookies.delete(:remember_token, domain: Rails.application.config.session_cookie_domain)
  end

  def admin_user
    redirect_to(root_url) unless current_user.admin?
  end

  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end

  def store_location
    session[:return_to] = request.url
  end

  def jkclient_agent?
    !!(request.env['HTTP_USER_AGENT'] =~ /JamKazam/)
  end

  # used to help GA tracking.  should result in one of Visitor, Registered User, or Paying Subscriber
  def ga_user_level
    if current_user.nil?
      'Visitor'
    else
      'Registered User'  # TODO: when paying subscriber exists, add to it
    end
  end

  # used to help GA tracking.  should result in either Fan or Musician
  def ga_user_type
    if current_user.nil?
      'Fan'
    else
      current_user.musician? ? 'Musician' : 'Fan'
    end
  end

  def logged_in_not_logged_in_class
    signed_in? ? "logged-in" : "not-logged-in"
  end


  def metronome_tempos
    [
      40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 63, 66, 69, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 126, 132, 138, 144, 152, 160, 168, 176, 184, 192, 200, 208
    ]
  end
end
