# $Id: mail.rb,v 1.18 2004/04/28 13:17:58 eto Exp $
# Copyright (C) 2003-2004 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 GPL2.

require 'kconv'
require 'qwik/config'

module Qwik
  class MailAddress
    def initialize(mail)
      @mail = mail.to_s
    end

    def to_s() @mail; end

    def valid?()
      return false if !@mail
      (/^([0-9a-zA-Z_.-]+)@([0-9a-zA-Z_.-]+)\.([0-9a-zA-Z_-]+)$/ =~ @mail) != nil
    end

    def obfuscate()
      @mail.sub(/(@.).*/, '\1...')
    end

    # foo@QuickML.CoM => foo@quickml.com
    # "foo"@example.com => foo@example.com
    def normalize()
      name, domain = @mail.split('@')
      name.gsub!(/^"(.*)"$/, '\1')
      return name + "@" + domain.downcase if domain
      @mail
    end

    def normalize!()
      @mail = normalize()
    end
  end

  class Mail
    def initialize(from=nil, to=nil, subject=nil, content=nil)
      @from, @to, @subject, @content = from, to, subject, content
    end
    attr_accessor :from, :to, :subject, :content
  end

  class Sendmail
    def initialize(config, host=nil, port=nil)
      @config = config
      @host, @port = host, port
      @host = @config.smtp_host if @host.nil?
      @port = @config.smtp_port if @port.nil?
#      @localmode = nil
    end
#    attr_accessor :localmode

    def sendmail(mail)
      send(mail.from, mail.to, mail.subject, mail.content)
    end

    def send(from, to, subject, content, host=@host, port=@port)
      efrom    = encode_field(from.to_s)
      eto      = encode_field(to.to_s)
      esubject = encode_field(subject)
      contentorg = <<EOM
From: #{efrom}
To: #{eto}
Subject: #{esubject}

#{content}
EOM
      content = contentorg.u8tojis
      if @config.test
	$smtp_sendmail = [host, port, from, to, content]
      else
	Net::SMTP.start(host, port) {|smtp|
	  smtp.send_mail(content, from, to)
	}
      end
      content
    end

    def send_qml(from, to, subject, content) # send mail to QuickML
      send(from, to, subject, content, @config.qml_host, @config.qml_port)
    end

    def encode_field (field)
      field.u8tosjis.gsub(Regexp.new("[\x81\x40-\xef\xf7]\\S*\\s*", nil, 's')) {|x|
	x.scan(Regexp.new(".{1,10}", nil, 's')).map {|y|
	  "=?iso-2022-jp?B?" + y.tojis.to_a.pack('m').chomp + "?="
	}.join("\n ")
      }
    end
  end
end
