# http://astashov.github.io/2011/02/26/conflict-of-session-cookies-with-different-domains-in-rails-3.html

# We had to do this when we changed from www.jamkazam.com to .jamkazam.com as the cookie served out

module Middlewares
  class ClearDuplicatedSession

    def log
      @log || Logging.logger[ClearDuplicatedSession]
    end

    def initialize(app)
      @app = app
    end

    def call(env)
      status, headers, body = @app.call(env)

      headers.each do|k,v|
        if k == 'Set-Cookie' && v.start_with?(get_session_key(env))
          bits = v.split(';')
          if bits.length > 0
            cookie_name_value = bits[0].split('=')
            if cookie_name_value.length == 1 && Rails.application.config.session_cookie_domain
              # this path indicates there is no value for the remember_token, i.e., it's being deleted
              ::Rack::Utils.set_cookie_header!(
                    headers, # contains response headers
                    get_session_key(env), # gets the cookie session name, '_session_cookie' - for this example
                    { :value => '', :path => '/', :expires => Time.at(0) })
            end
          end
        end
      end
      if there_are_more_than_one_session_key_in_cookies?(env)
        delete_session_cookie_for_current_domain(env, headers)
      end

      [status, headers, body]
    end


    private

    def there_are_more_than_one_session_key_in_cookies?(env)
      entries = 0
      offset = 0
      while offset = env["HTTP_COOKIE"].to_s.index(get_session_key(env), offset)
        entries += 1
        offset += 1
      end
      entries > 1
    end


    # Sets expiration date = 1970-01-01 to the cookie, this way browser will
    # note the cookie is expired and will delete it
    def delete_session_cookie_for_current_domain(env, headers)
      log.debug "deleting default domain session cookie"
      ::Rack::Utils.set_cookie_header!(
          headers, # contains response headers
          get_session_key(env), # gets the cookie session name, '_session_cookie' - for this example
          { :value => '', :path => '/', :expires => Time.at(0) }
      )
    end


    def get_session_key(env)
      'remember_token'
    end

  end
end