module JamRuby

  # some times someone comes to signup as a new user, but there is context to preserve.
  # the AnyUser cookie is one way that we can track the user from pre-signup to post-signup
  # anyway, once the signup is done, we check to see if there is a SignupHint, and if so,
  # we use it to figure out what to do with the user after they signup
  class SignupHint < ActiveRecord::Base

    belongs_to :jam_track, class_name: 'JamRuby::JamTrack'

    belongs_to :user, class_name: 'JamRuby::User'

    validates :redirect_location, length: {maximum: 1000}
    validates :want_jamblaster, inclusion: {in: [nil, true, false]}

    def self.create_redirect(user, options = {})
      hint = SignupHint.new
      hint.user = user
      hint.redirect_location = options[:redirect_location] if options.has_key?(:redirect_location)
      hint.want_jamblaster = false
      hint.expires_at = 2.days.from_now
      hint.save
      hint
    end

    def self.refresh_by_anoymous_user(anonymous_user, options = {})

      hint = SignupHint.find_by_anonymous_user_id(anonymous_user.id)

      unless hint
        hint = SignupHint.new
      end

      hint.anonymous_user_id = anonymous_user.id
      hint.redirect_location = options[:redirect_location] if options.has_key?(:redirect_location)
      hint.want_jamblaster = options[:want_jamblaster] if options.has_key?(:want_jamblaster)
      #hint.jam_track = JamTrack.find(options[:jam_track]) if options.has_key?(:jam_track)
      hint.expires_at = 15.minutes.from_now
      hint.save
      hint
    end

    def self.delete_old
      SignupHint.where("created_at < :week", {:week => 1.week.ago}).delete_all
    end

    def self.most_recent_redirect(user, default, queryParams=nil)
      puts "jquery params"
      hint = SignupHint.where(user_id: user.id).order('created_at desc').first

      if hint
        redirect = hint.redirect_location
        puts "redirect #{redirect}"
        uri =  URI.parse(redirect)
        bits = uri.query ? URI.decode_www_form(uri.query) : []
        if queryParams
          queryParams.each do |k, v|
            bits << [k, v]
          end
        end

        puts "bits #{bits}"
        uri.query = URI.encode_www_form(bits)
        puts "oh yeah #{uri.to_s}"
        return uri.to_s
      else
        default
      end
    end
  end
end
