require "nkf"
require "web/controller/simple"
require "simplebbs/model"
require "simplebbs/view/board"

module Simplebbs
  class Controller < Web::Controller::Simple
    include Simplebbs::View::Board
    
    def initialize
      @model = nil
    end
    
    def version
      'simplebbs 0.0.1'
    end
    
    def setup(opt)
      @name  = opt[:name] || 'mwbbs'
      @model = Simplebbs::Model.new(opt)
    end
    
    def teardown
      @model.close
    end
    
    def board_name
      h @name
    end

    ARG_top = Struct.new(:subject, :from, :mail, :text, :msglist, :id_from, :id_to)
    def do_start(req, rsp)
      arg = ARG_top.new
      arg.subject = ''
      arg.from    = ''
      arg.mail    = ''
      arg.text    = ''
      
      arg.id_from = get_param(req, 'from', :integer, false) || @model.get_max_id
      arg.id_to   = arg.id_from - 20
      
      arg.msglist = @model.get_msglist(arg.id_from,arg.id_to)
      rsp.content_type = "text/html; charset=EUC-JP"
      rsp << top(arg)
    end

    def do_post(req, rsp)
      msgdate = Time.now.localtime.strftime("%Y/%m/%d %H:%M:%S")
      from    = NKF.nkf('-m0 -eXd', get_param(req, 'from', :text).strip)
      mail    = get_param(req, 'mail', :text).strip
      subject = get_param(req, 'subject', :text).strip
      message = NKF.nkf('-m0 -eXd', get_param(req, 'text', :text)).strip
      begin
        raise if (from.empty? || subject.empty? || message.empty?)
        id_from = @model.get_max_id
        msglist = @model.get_msglist(id_from,id_from)
        if msg=msglist.first
          raise if msg.message == message
        end
        @model.insert(msgdate, from, mail, subject, message)
      rescue
        #
      end
      #
      arg = ARG_top.new
      arg.subject = ''
      arg.from    = from
      arg.mail    = mail
      arg.text    = ''
      arg.id_from = @model.get_max_id
      arg.id_to   = arg.id_from - 20
      if arg.id_to < 1
        arg.id_to = 1
      end
      arg.msglist = @model.get_msglist(arg.id_from,arg.id_to)
      rsp.content_type = "text/html; charset=EUC-JP"
      rsp << top(arg)
    end
    
    def msg2html(text)
      html = h(text)
      html.gsub!(/\r?\n/,"<br>")
      html.gsub!(/(http:\/\/[a-zA-Z0-9_?\#\+\-\.%&=\/]+)/) { "<a href=\"#{$1}\">#{$1}</a>" }
      html
    end
  end
end
