#--
# Copyright (c) 2007 Robert S. Thau, Smartleaf, Inc.
# 
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
class RequestLogEntry < ActiveRecord::Base

  has_many :pcheck_log_entries

  cattr_accessor :current

  def self.logging( controller, request, response )

    begin

      unless self.current.nil?
        raise RuntimeError, "Can't nest RequestLogEntry.logging"
      end

      self.current = self.new
      yield

    ensure

      entry = self.current
      self.current = nil

      unless User.current.nil?
        entry.acting_user_id   = User.current.id
        entry.acting_user_name = User.current.name
      end

      unless User.of_record.nil?
        entry.user_of_record_id   = User.of_record.id
        entry.user_of_record_name = User.of_record.name
      end

      entry.controller = controller.class.name
      entry.action     = controller.action_name

      entry.remote_ip   = request.remote_ip || 'UNKNOWN'
      entry.http_method = request.method.to_s
      entry.status      = response.headers["Status"] || 'UNKNOWN'

      if controller.respond_to?( :resource ) && !controller.resource.nil?
      
        model_object = controller.resource

        entry.model_class = model_object.class.name
        entry.model_id    = model_object.id

      end

      entry.save!
      entry.save_logged_pchecks!

    end

  end
  
  attr_accessor :logged_pchecks

  def self.new( attrs = {} )
    super attrs.merge( :logged_pchecks => [] )
  end

  def self.note_pcheck( pcheck_hash )
    unless self.current.nil?
      self.current.logged_pchecks << pcheck_hash
    end
  end

  def save_logged_pchecks!

    # Could do some kind of fast bulk create here, to avoid AR overhead...

    logged_pchecks.each do |attrs|
      self.pcheck_log_entries.create! attrs
    end

  end

  Smartguard::Logging.add_hook { |h| self.note_pcheck( h ) } 

end

