# -*- mode: ruby; -*-
#=begin header
#Operator命令処理エージェント
#  ぷりぶで来た!ではじまる命令に反応します。
#
#  $Author: knu $
#  $Date: 2001/01/31 10:55:28 $
#
#  Copyright (C) 1998-2000 Hiroshi IGARASHI
#=end

agent = IRC::PassiveAgent::new("Operator命令")

class << agent
  include IRC
  def start(client)
    super
    @operator = User.parse(Operator)
    report("こんにちわ")
  end
  def stop
    super
  end
  def notifyMessage(message)
      case message.command
      when CMD_PRIVMSG
        from = message.prefix
        to = message.params[0]
        user = User::parse(from)
        #putlog("debug", "recieved PRIVMSG from #{user}.")
        str = message.trailing
        if to == @client.nick
          if user.nick == @operator.nick
            operator(str)
          else
            report("#{user}さんが「#{str}」だって。")
          end
        end
      end
  end

  private
  def report(str)
    privmsg("!"+str, @operator.nick)
  end
  def operator(str)
    if str =~ /\A[\s ]*[!!](.*)[\s ]*\Z/
      putlog("debug", $1)
      str = $1
      case str
      when /\A(?:quit|停止|ばいばい)\Z/
        doQuit
      when /\A(?:reboot|再起動)\Z/
        doReboot
      when /\A(?:エージェント|えーじぇんと|listAgent)\Z/
        doListAgent
      when /\A(?:restartAgent|えーじぇんとさいきどう|エージェント再起動)[\s ]+(\w+)\Z/
        doRestartAgent($1)
      when /\A(?:channels|ちゃんねる|チャンネル)\Z/
        doMychannel
      when /\A(?:invite|おいで)[\s ]+(\S+)\Z/
        doInvite($1)
      else
        report("ほえ?")
      end
    end
  end

  # 終了
  def doQuit
    report("ばいば~い☆")
    @client.stop
  end

  # 再起動(to be fixed)
  def doReboot
    unless fork
      exec($0)
    end
    doQuit
  end

  # エージェント:一覧
  def doListAgent
    report("エージェント一覧:")
    @client.agents.keys.sort.each do |name|
      agent = @client.agents[name]
      putlog("debug", agent.inspect)
      report("  #{agent.script_name.ljust(24)}: #{agent.nick}")
    end
    report("(エージェント一覧ここまで)")
  end

  # エージェント:再起動
  def doRestartAgent(name)
    new_agent = @client.restartAgent(name)
    unless new_agent.nil?
      report("エージェント[#{new_agent.nick}]を再起動しました。")
    end
  end

  # 自分の入っているチャンネル
  def doMychannel
    channels = @client.join_channels
    unless channels.empty?
      report("今入っているちゃんねるは")
      report(" " + channels.join(","))
      report("だよ。")
    else
      report("今どのチャンネルにも入ってないよ")
    end
  end

  def doInvite(channel)
    report(channel+"にいきます。")
    @client.join(channel, [])
    privmsg("こんにちわ、おじゃましま~す☆", channel)
    putlog("join", channel)
  end
end

agent