#
# Copyright (C) 2002-2004 Satoru Takabayashi <satoru@namazu.org> 
# Copyright (C) 2003-2005 Kouichirou Eto
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms of 
# the GNU General Public License version 2.
#

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/ml-exception"

module QuickML
  # It preserves case information. but it accepts an
  # address case-insensitively for member management.
  class IcaseArray < Array
    def include? (item)
      if self.find {|x| x.downcase == item.downcase } 
	true
      else
	false
      end
    end

    def delete (item)
      self.replace(self.find_all {|x| x.downcase != item.downcase })
    end
  end

  class IcaseHash < Hash
    def include? (key)
      super(key.downcase)
    end

    def delete (key)
      super(key.downcase)
    end

    def [] (key)
      super(key.downcase)
    end	

    def []= (key, value)
      super(key.downcase, value)
    end	
  end

  class ErrorInfo
    def initialize (count = 0, last_error_time = Time.at(0))
      @count = count
      @last_error_time = last_error_time
    end
    attr_reader :count
    attr_reader :last_error_time

    def inc_count
      @count += 1
      @last_error_time = Time.now
    end
  end

  class ErrorMailHandler
    def initialize (config, message_charset)
      @config = config
      @logger = config.logger
      @message_charset = message_charset
    end

    def handle (mail)
      if /^(.*)=return=(.*?)@(.*?)$/ =~ mail.recipients.first
	mladdress = $1 + "@" + $3
	error_address = $2.sub(/=/, "@")
 	@config.ml_mutex(mladdress).synchronize {
	  ml = QuickML.new(@config, mladdress, nil, @message_charset)
 	  handle_error(ml, error_address)
 	}
      else
	@logger.vlog "Error: Use Postfix with XVERP to handle an error mail!"
      end
    end

    private

    def handle_error (ml, error_address)
      @logger.log "ErrorMail: [#{ml.name}] #{error_address}"
      ml.add_error_member(error_address)
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  $debug = true
end

if $debug
  class TestMCoreUtils < Test::Unit::TestCase
    def test_all
      # test_iscase_array
      iar = QuickML::IcaseArray.new
      iar << "T"
      assert_equal(true, iar.include?("T"))
      assert_equal(true, iar.include?("t"))
      iar.delete("t")
      assert_equal(false, iar.include?("t"))

      # IcaseHash
      ih = QuickML::IcaseHash.new
      ih["T"] = 1
      assert_equal(true, ih.include?("t"))
      assert_equal(1, ih["t"])
      ih.delete("t")
      assert_equal(false, ih.include?("t"))
    end
  end
end
