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

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

c = CGI.new(:tag_maker => "html5", :accept_charest => "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,job,stamp_status,stamp_img,exp INTEGER,rank INTEGER,magic)");
  db.execute("insert into main(name,sex,age,aria,job,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"]
job  = c["job"]
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=?, job=?, age=?, sex=?, aria=? where id=? and magic=?'
mg = c_magic
db.execute(update, name, job, 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,job,stamp_status,stamp_img,exp,rank,magic) values (?,?,?,?,?,?,?,?,?,?);"
db.execute(sql,name,sex,age,aria,job,'000010000','n,n,n,n,kamo1,n,n,n,n',0,0,mg); #初期値
end

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

printf("Content-type: text/html; charset=UTF-8
Set-Cookie:id=%s ;expires=%s
Set-Cookie:magic=%s;expires=%s\n\n",id,expires,mg.to_s,expires)

print'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Registering Account</title>
<link rel="stylesheet" type="text/css" href="design.css">
</head>'
printf'
<p>登録が完了しました。</p>
<p>あなたのIDは%04dです。抽選はこのIDを元に行われます</p>
<p>下記リンクからスタンプラリーを開始して下さい!</p>
<p><a href="Bingo.rb"> >> Let\'s go to Stamp Rally << </a></p>
<p></p>

</body></html>
',id.to_i-1
