//sqlite3に保存する機能完成
//http://www.nct9.ne.jp/m_hiroi/light/node03.html
const http = require('http'),
fs = require('fs'),
ejs = require('ejs'),
qs = require('querystring'),
sqlite = require('sqlite3'),
template = fs.readFileSync(__dirname + '/public_html/bbs1.ejs', 'utf-8'),
db = new sqlite.Database(__dirname + '/public_html/bbs.sqlite'),
server = http.createServer();

function renderForm(db, res, msg = null) {
db.all('select * from bbs', (err, posts) => {
const data = ejs.render(template, {
posts: posts,
msg: msg
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}

function insertData(query, db, res) {
if (query.name != '' && query.comment != '') { 
db.run('insert into bbs (name, comment, date) values (?, ?, ?)',
     [query.name, query.comment, (new Date()).toLocaleString()]);
renderForm(db, res);
} else {
renderForm(db, res, "名前とコメントを入力してください");
}
}

db.serialize();
db.run('create table if not exists bbs (id integer primary key autoincrement, name text, comment text, date text)');

server.on('request', (req, res) => {
if (req.method == 'POST') {
let data = "";
req.on('data', x => data += x);
req.on('end', () => insertData(qs.parse(data), db, res));
} else {
renderForm(db, res);
}
});

server.listen(2022, 'localhost');
console.log("server listening...");