#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'cgi'
require 'sqlite3'
require './magic.rb'

c = CGI.new(:accept_charset => "UTF-8")
db = SQLite3::Database.new("./sql/stamp.sq3")

begin
  result = db.execute("select * from main;")
  max = "select max(id) from main;"
rescue
  db.execute("create table main(id INTEGER PRIMARY KEY AUTOINCREMENT,name,sex,age,aria,cal,stamp_status,stamp_img,exp INTEGER,rank INTEGER,magic)");
  db.execute("insert into main(name,sex,age,aria,cal,stamp_status,stamp_img,exp,rank,magic) values('名前','性別','年代','住所','職業','スタンプ状況','スタンプ画像','レベル','当選順位','本人確認用')");
  result = db.execute("select * from main;")
  max = "select max(id) from main;"
end

id = c.cookies["id"][0]
c_magic = c.cookies["magic"][0]
name = c["name"]
cal  = c["cal"]
age  = c["age"]
sex  = c["sex"]
aria = c["aria"]

begin
sel = 'select * from main where id=? AND magic=?'
h = db.execute(sel, id.to_i, c_magic.to_i)
rescue
h == []
end

if id != nil && h != []
update = 'update main set name=?, cal=?, age=?, sex=?, aria=? where id=? and magic=?'
mg = c_magic
db.execute(update, name, cal, age, sex, aria, id.to_i, mg.to_i)
else
code = magic()
id = db.execute(max).flatten(2)[0].to_i + 1
mg = code[id]
sql = "insert into main(name,sex,age,aria,cal,stamp_status,stamp_img,exp,rank,magic) values (?,?,?,?,?,?,?,?,?,?);"
db.execute(sql,name,sex,age,aria,cal,'000010000','n,n,n,n,kamo1,n,n,n,n',0,0,mg); #初期値
end

expires = "SAT, 26 Oct 2015 00:00:00 GMT"


printf(<<_EOS_,id, expries, mg.to_s, exprires)
Content-type: text/html; charset=UTF-8
Set-Cookie:id=%s ;expires=%s
Set-Cookie:magic=%s;expires=%s

<html>
<head>
<title>#{id}</title>
<link rel="stylesheet" type="text/css" href="../cssrubyII.css">
</head>
<body>
<p>
・#{name}<br>・#{cal}<br>・#{age}<br>・#{sex}<br>・#{aria}<br>・#{id}
</p>

<p>
tukaretanaaaa、#{names}
</p>
</body>
</html>
_EOS_
