#!/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

name = c["name"]
job  = c["job"]
age  = c["age"]
sex  = c["sex"]
aria = c["aria"]

code = magic()
#id = result.length
id = db.execute(max).flatten(2)[0].to_i + 1
#printf("%04d",id)

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,kamo,n,n,n,n',1,0,mg); #初期値

expires = "Sun, 27 Jul 2016 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>'
print'
<p>登録が完了しました。下記リンクからスタンプラリーを開始して下さい!</p>
<p><a href="Bingo.rb"> >> Let\'s go to Stamp Rally << </a></p>
<p></p>

</body></html>
'
