# encoding: utf-8
# alone : web application framework for small embedded systems.
#               Copyright (c) 2010 FAR END Technologies Corporation.
#               All Rights Reserved.
#
# This file is destributed under BSD License. Please read the COPYRIGHT file.

require 'nkf'
require 'al_template'
require 'al_form'

class AlController
  MAIL_SUBJECT = 'お問い合わせ'
  MAIL_FROM = 'your-server@example.net'
  RCPT_TO = 'recipient@example.com'
  
  def action_index
    @form = make_contact_form

    if @form.fetch_request('POST') && @form.validate then
      @order_detail = mail_body(@form)
      send_mail(:from => MAIL_FROM, :to => RCPT_TO,
                :subject => MAIL_SUBJECT,
                :reply_to => @form.values[:mail], :body => @order_detail)
      @part_template = '_thanks.html'
    else
      @part_template = '_contact.html'
    end

    # layout.html内で @part_template に設定したテンプレートが読み込まれる
    AlTemplate.run 'layout.html'
  end

  private
  def make_contact_form
    form = AlForm.new
    form.set_widgets(
      AlText.new('name', :label => 'お名前', :required => true, :tag_attr => {:size => 20}),
      AlMail.new('mail', :label => 'メールアドレス', :required => true, :tag_attr => {:size => 40}),
      AlText.new('company', :label => '会社・団体名', :required => false, :tag_attr => {:size => 40}),
      AlText.new('phone', :label => '電話番号', :required => false, :tag_attr => {:size => 14}),
      AlText.new('subject', :label => '件名', :required => true, :tag_attr => {:size => 40}),
      AlTextArea.new('message', :label => '内容', :required => true, :cols => 40, :rows => 8),
      AlSubmit.new('submit', :value => '問い合わせ送信')
    )
    return form
  end

  # メール送信処理
  def send_mail(params)
    mail_from = params[:from] || raise(':from is required.')
    mail_to = params[:to] || raise(':to is required.')
    mail_subject = params[:subject]
    reply_to = params[:reply_to]
    mail_body = params[:body]

    open("|/usr/sbin/sendmail -f #{mail_from} #{mail_to}", "w") do |m|
      m.puts "Subject: =?utf-8?B?#{NKF.nkf("-wMB", mail_subject)}?="
      m.puts "To: #{mail_to}"
      m.puts "To: #{mail_from}"
      m.puts "Reply-to: #{reply_to}" if reply_to
      m.puts "Content-Type: text/plain; charset=utf-8"
      m.puts
      m.puts mail_body
    end
  end

  # フォームの値からメールの本文を生成
  def mail_body(form)
    body = ''
    form.widgets.each do |k, w|
      next if w.is_a?(AlSubmit)
      body << "【%s】\n%s\n\n" % [w.label, w.value]
    end
    return body
  end
end
