#!/usr/local/bin/ruby -Ke
require "dbi"

module Simplebbs
  class Model
    def initialize(opt)
      @dbh = DBI.connect(opt[:conn], opt[:uid], opt[:pwd])
    end
    attr_accessor :dbh

    def close
      @dbh.disconnect
    end
    
    def get_max_id
      row = @dbh.select_one('SELECT max(msg_id) FROM messages')
      if row
        row.first.to_i
      else
        1
      end
    end

    Row_msglist = Struct.new(:msg_id, :msgdate, :name, :mail, :subject, :message)
    def get_msglist(from,to)
      msglist = []
      @dbh.execute('SELECT msg_id, msgdate, name, mail, subject, message  FROM messages WHERE msg_id <= ? and msg_id >= ? ORDER BY msg_id DESC', from, to) {|sth|
        sth.each {|row|
          row = Row_msglist.new(*row)
          msglist << row
        }
      }
      msglist
    end

    SQL_INSERT = <<-EOS
      INSERT INTO messages(
        msg_id,
        msgdate,
        name,
        mail,
        subject,
        message
      )
      VALUES(?,?,?,?,?,?)
    EOS
    def insert(msgdate, name, mail, subject, message)
      msg_id = get_max_id + 1
      @dbh.execute(SQL_INSERT, msg_id, msgdate, name, mail, subject, message)
      @dbh.commit
    end
  end
end
