#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
Encoding.default_external = 'utf-8'

require'cgi'
require'open3'
require'sqlite3'
require'timeout'
require'csv'
  
c = CGI.new(:accept_charset => "UTF-8")

begin
Timeout.timeout(0.1){
print"Content-type: text/html; charset=utf-8\n\n"

coderead = c["example"]
namae = c["name"]
ans = c["ans"].delete("\r")
newans = ans.strip

if /system|exec|open/ =~ coderead
  file = File.open("no.txt", "r")
  puts file.read
  file.close
  exit
end

cmd = "ruby -Ku -e '#{coderead}'"
o,e,s = Open3.capture3(cmd) #o,e,s = 実行結果、エラー文、プロセス？
newo = o.strip


print <<EOF
<DOCTYPE html>
  <head> 
    <meta charset=utf-8>
    <title>テキストエディタ読み込み</title>
    <link rel="stylesheet" type="text/css" href="root/editor.css">
    <style>
<!--
-->
    </style>
  </head>
  <body>

  <div class="mondai">
  <h1 class="sen1">結果画面</h1>
  </div>


EOF

puts("<div class=\"editor\">")
puts("<h1><span class=\"waku1\">入力したコード</span></h1>")
printf("<textarea name=\"example\" readonly=\"readonly\">%s</textarea>", coderead)
puts("</div>")

puts("<div class=\"ex\">")
puts("<h1><span class=\"waku1\">実行結果</span></h1>")
puts("<div>")
printf("<pre>%s</pre>", o) #evalでRubyコードとして読み込む
puts("</div>")
puts("</div>")


puts("<div class=\"kekka\">")
if newans == newo
  puts("<h2><span class=\"sucsess\">sucsess!!</span></h2>")
else
  puts("<h2><span class=\"no\">NO!!!実行結果が違います</span></h2>")
end 

if e != ""
  puts("<h2><span class=\"waku1\">エラー文</span></h2>")
  printf("<p>%s</p>\n", e)
  remess = e.split(" ")
  open("err.csv", "r") do |f|
    while line = f.gets
      if /^#/ =~ line
        next
      elsif /(.+),(.+)/ =~ line
        for i in 0..remess.length
          if remess[i].to_s.include?($1)
            printf("<h4>[<a href=\"https://www.google.com/search?q=%s+ruby\">%s</a>]→%s</h4>\n", $1, $1 ,$2)
          end
        end
      end
    end
  end

else
  print("<p>エラー文はないよ！</p>")
end

puts("</div>")

puts("<div class=\"send\">")
puts("<a href=\"./editor.rb\">エディタ画面へ戻る</a>")
puts("</div>")

puts("</body>\n</html>")
  
}
rescue Timeout::Error
  file = File.open("errormes.txt", "r")
  puts file.read
  file.close
end
