# Copyright (c) 2010, Takaya Kakizaki(kacky)
# All rights reserved.
#
#  ソースコード形式かバイナリ形式か、変更するかしないかを問わず、以下の条件を満たす場合に限り、再頒布および使用が許可されます。 
#
#  ・ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、および下記免責条項を含めること。 
#
#  ・バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の資料に、上記の著作権表示、本条件一覧、および下記免責条項を含めること。 
#
#  ・書面による特別の許可なしに、本ソフトウェアから派生した製品の宣伝または販売促進に、オープン麻雀の名前またはコントリビューターの名前を使用してはならない。
#
#
#  本ソフトウェアは、著作権者およびコントリビューターによって「現状のまま」提供されており、明示黙示を問わず、
#  商業的な使用可能性、および特定の目的に対する適合性に関する暗黙の保証も含め、またそれに限定されない、いかなる保証もありません。
#  著作権者もコントリビューターも、事由のいかんを問わず、 損害発生の原因いかんを問わず、かつ責任の根拠が契約であるか厳格責任であるか
#  （過失その他の）不法行為であるかを問わず、仮にそのような損害が発生する可能性を知らされていたとしても、本ソフトウェアの使用によって発生した
#  （代替品または代用サービスの調達、使用の喪失、データの喪失、利益の喪失、業務の中断も含め、またそれに限定されない）
#  直接損害、間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害について、一切責任を負わないものとします。 
require "mahjongserver"
require "rexml/document"
require "kconv"

def unknowncommand(str)
  puts "unknown command : #{str}"
end

def printstate(root,selectPlayer)
  sname = root.elements["state/name"].text
  kyokucount = root.elements["taku/kyokucount"].text.to_i
  kyokutable = ["東一局","東二局","東三局","東四局","南一局","南二局","南三局","南四局"]
  ietable = ["東家","南家","西家","北家"]
  eventtable = ["打牌","チー","ポン","カン","カン","カン","ロン","ツモ","リーチ","パス","九種九牌倒牌","四風子連打","四人リーチ","荒牌","四カンツ流れ","三家和","半荘終了","局開始"]
  
  ev = root.elements["taku/event/command/type"];
  if ev
    event_type = ev.text.to_i
  else
    event_type = 0
  end
  
  puts "state : #{sname}"
  puts
  
  if event_type > 0
    puts "event : #{eventtable[event_type - 100]}"
  end
  
  result = root.elements["taku/event/result"]
  
  if result
    result.elements.each("yaku") { | element |
      print "#{element.text.toeuc} "
    }
    puts
    puts "#{result.elements["han"].text}翻 #{result.elements["fu"].text}符 #{result.elements["score"].text}点"
  end
  
  puts "#{kyokutable[kyokucount]} 残り : #{root.elements["taku/yama/count"].text}"
  print "ドラ "
  root.elements.each("taku/dora/pai") { | element |
    pai = Pai.new
    pai.category = element.elements["category"].text.to_i
    pai.no = element.elements["no"].text.to_i
    pai.id = element.elements["id"].text.to_i
    
    dora = pai.getDora
    
    print "#{dora.getName} "
  }
  
  puts
  
  root.elements.each("taku/member") { | element |
    if element.elements["player/id"].text.to_i == selectPlayer.id
      $own = element.elements
    else
      puts "ライバル"
      puts "#{element.elements["player/name"].text} #{ietable[element.elements["gamestate/zikaze"].text.to_i-1]}"
      print "点数 : #{element.elements["point"].text}"
      if element.elements["gamestate/riichi"].text == "true"
        print "** リーチ **"
      end
      
      puts
      print "打牌 "
      $i = 1
      element.elements.each("dahai/pai") { | element |
        pai = Pai.new
        pai.category = element.elements["category"].text.to_i
        pai.no = element.elements["no"].text.to_i
        pai.id = element.elements["id"].text.to_i
        
        print "[#{$i-1}]#{pai.getName} "
        $i += 1
      }
      puts
    end
  }
  
  puts "プレーヤ"
  puts "#{$own["player/name"].text} #{ietable[$own["gamestate/zikaze"].text.to_i-1]}"
  print "点数 : #{$own["point"].text}"
  if $own["gamestate/riichi"].text == "true"
    print "** リーチ **"
  end
  puts
  
  $i = 1
  print "打牌 "
  $own.each("dahai/pai") { | element |
    pai = Pai.new
    pai.category = element.elements["category"].text.to_i
    pai.no = element.elements["no"].text.to_i
    pai.id = element.elements["id"].text.to_i
    
    print "[#{$i-1}]#{pai.getName} "
    $i += 1
  }
  puts
  print "手牌 "
  $i = 1
  $own.each("tehai/pai") { | element |
    pai = Pai.new
    pai.category = element.elements["category"].text.to_i
    pai.no = element.elements["no"].text.to_i
    pai.id = element.elements["id"].text.to_i
    
    print "[#{$i-1}]#{pai.getName} "
    $i += 1
  }
  
  puts
  puts "コマンド"
  
  $own.each("commandlist/command") { | element |
    id = element.elements["id"].text.to_i
    if id >= ID_RIICHI && id <= ID_RIICHI + 13
      pai = Pai.new
      pai.category = element.elements["pai/category"].text.to_i
      pai.no = element.elements["pai/no"].text.to_i
      pai.id = element.elements["pai/id"].text.to_i
      print "[#{id}] リーチ #{pai.getName} "
    end
    if id == ID_TSUMO
      print "[#{id}] ツモ "
    end
    if id == ID_START
      print "[#{id}] 次の局へ "
    end
    if id == ID_PASS
      print "[#{id}] 鳴かない "
    end
    if id >= ID_TII && id < ID_PON
      print "[#{id}] チー "
      element.elements.each("mentsu/pai") { | item |
        pai = Pai.new
        pai.category = item.elements["category"].text.to_i
        pai.no = item.elements["no"].text.to_i
        pai.id = item.elements["id"].text.to_i
        print "#{pai.getName} "
      }
    end
    if id >= ID_PON && id < ID_DAIMINKAN
      pai = Pai.new
      pai.category = element.elements["pai/category"].text.to_i
      pai.no = element.elements["pai/no"].text.to_i
      pai.id = element.elements["pai/id"].text.to_i
      print "[#{id}] ポン #{pai.getName} "
    end
    
    if id == ID_DAIMINKAN
      pai = Pai.new
      pai.category = element.elements["pai/category"].text.to_i
      pai.no = element.elements["pai/no"].text.to_i
      pai.id = element.elements["pai/id"].text.to_i
      print "[#{id}] カン #{pai.getName} "
    end
    
    if id == ID_RON
      pai = Pai.new
      pai.category = element.elements["pai/category"].text.to_i
      pai.no = element.elements["pai/no"].text.to_i
      pai.id = element.elements["pai/id"].text.to_i
      print "[#{id}] ロン #{pai.getName} "
    end
  }
  
  puts
end


# コマンドラインによるデバッグプログラム by Kakizaki

players = [] # プレイヤーストック
selectPlayer = nil # プレイヤーセレクト
sessionid = -1


puts "welcome to open mahjong project console.\n"



while true
  print "command : "
  str = STDIN.gets
  
  str.chomp!
  
  args = str.split(" ")
  
  doc = REXML::Document.new
  root = doc.add_element("openmahjongclient",{"version" => "0.1"})
  
  
  if args[0] == "cre"
    if args.length < 2
      puts "few argments #{args.length}"
      next
    end
    
    if args[1] == "s"
      if !selectPlayer
        puts "please create player"
        next
      end
      
      command = Command.new
      command.id = ID_CREATE
      command.player = selectPlayer
      root.push(command.getElement)
      root.add_attribute("session","-1")
      
      buf = ""
      
      doc.write(buf)
      
      puts "--------- request ------------"
      puts buf
      puts "------- request end ----------"
      
      res = sendRequest(buf)
      puts "--------- responce ------------"
      puts res
      puts "------- responce end ----------"
      puts "OK"
      
      resdoc = REXML::Document.new res
      
      root = resdoc.root
      
      # セッションIDとプレーヤーIDをセット
      sessionid = (root.attribute("session").to_s).to_i
      playid = root.elements["responce/command/player/id"].text.to_i
      selectPlayer.id = playid
      
    elsif args[1] == "p"
      if args.length < 3
        puts "few argments #{args.length}\n"
        next
      end
      p = Player.new
      p.name = args[2]
      players.push(p)
      selectPlayer = p
      puts "OK\n"
    else
      unknowncommand(str)
    end
  elsif args[0].to_i > 0
    if !selectPlayer
      puts "please create player"
      next
    end
    
    root.add_attribute("session",sessionid.to_s)
    command = Command.new
    command.id = args[0].to_i
    command.player = selectPlayer
    root.push(command.getElement)
    
    buf = ""
    
    doc.write(buf)
    
    puts "--------- request ------------"
    puts buf
    puts "------- request end ----------"
    
    res = sendRequest(buf)
    puts "--------- responce ------------"
    puts res
    puts "------- responce end ----------"
    puts "OK"
    
    for player in players
      doc = REXML::Document.new
      root = doc.add_element("openmahjongclient",{"version" => "0.1"})
      root.add_attribute("session",sessionid.to_s)
      command = Command.new
      command.id = ID_STATUS
      command.player = player
      root.push(command.getElement)
      buf = ""
      
      doc.write(buf)
      
      puts "--------- request ------------"
      puts buf
      puts "------- request end ----------"
      
      res = sendRequest(buf)
      puts "--------- responce ------------"
      puts res
      puts "------- responce end ----------"
      puts "OK"
    end
    
    for player in players
      doc = REXML::Document.new
      root = doc.add_element("openmahjongclient",{"version" => "0.1"})
      root.add_attribute("session",sessionid.to_s)
      command = Command.new
      command.id = ID_STATUS
      command.player = player
      root.push(command.getElement)
      buf = ""
      
      doc.write(buf)
      
      puts "--------- request ------------"
      puts buf
      puts "------- request end ----------"
      
      res = sendRequest(buf)
      puts "--------- responce ------------"
      puts res
      puts "------- responce end ----------"
      puts "OK"
      resdoc = REXML::Document.new res
      root = resdoc.root
      
      if root.elements["state/code"].text == "102"
        selectPlayer = player
        seldoc = resdoc
      end
    end
    
    root = seldoc.root
    printstate(root,selectPlayer)
  elsif args[0] == "sel"
    bFind = false
    if args.length < 2
      puts "few argments #{args.length}"
      next
    end
    
    for player in players
      if player.name == args[1]
        selectPlayer = player
        bFind = true
        break
      end
    end
    
    if bFind
      puts "OK\n"
    else
      puts "Cannot find #{args[1]}"
    end
    
  elsif args[0] == "con"
    root.add_attribute("session",sessionid.to_s)
    
    if !selectPlayer
      puts "please create player"
      next
    end
    command = Command.new
    command.id = ID_CONNECT
    command.player = selectPlayer
    root.push(command.getElement)
    
    buf = ""
    
    doc.write(buf)
    
    puts "--------- request ------------"
    puts buf
    puts "------- request end ----------"
    
    res = sendRequest(buf)
    puts "--------- responce ------------"
    puts res
    puts "------- responce end ----------"
    puts "OK"
    resdoc = REXML::Document.new res
      
    root = resdoc.root
    # プレーヤーIDをセット
    playid = root.elements["responce/command/player/id"].text.to_i
    selectPlayer.id = playid
  elsif args[0] == "com"
    if !selectPlayer
      puts "please create player"
      next
    end
    
    if args.length < 2
      puts "few argments #{args.length}"
      next
    end
    root.add_attribute("session",sessionid.to_s)
    command = Command.new
    command.id = args[1].to_i
    command.player = selectPlayer
    root.push(command.getElement)
    
    buf = ""
    
    doc.write(buf)
    
    puts "--------- request ------------"
    puts buf
    puts "------- request end ----------"
    
    res = sendRequest(buf)
    puts "--------- responce ------------"
    puts res
    puts "------- responce end ----------"
    puts "OK"
    resdoc = REXML::Document.new res
      
    root = resdoc.root
    
    if command.id == ID_STATUS && root.elements["responce/code"].text == "200"
      printstate(root,selectPlayer)
    end
  elsif args[0] == "debug"
    sessionid = args[1].to_i
    command = Command.new
    command.id = ID_DEBUG
    root.add_attribute("session",sessionid.to_s)
    root.push(command.getElement)
    buf = ""
    
    doc.write(buf)
    
    puts "--------- request ------------"
    puts buf
    puts "------- request end ----------"
    
    res = sendRequest(buf)
    puts "--------- responce ------------"
    puts res
    puts "------- responce end ----------"
    puts "OK"
    resdoc = REXML::Document.new res
      
    root = resdoc.root
    
    players = []
    root.elements.each("taku/member") { | element |
      player = Player.new
      player.id = element.elements["player/id"].text.to_i
      player.name = element.elements["player/name"].text
      players.push(player)
    }
    
  elsif args[0] == "exit"
    puts "program exit."
    break
  else
    unknowncommand(str)
  end
  
end


