//node.jsだけでチャット機能を作る方法
//http://www.nct9.ne.jp/m_hiroi/light/node02.html
const http = require('http'),
      fs = require('fs'),
      ejs = require('ejs'),
      url = require('url'),
      qs = require('querystring'),
      template = fs.readFileSync(__dirname + '/bbs.ejs', 'utf-8'),
      posts = [],
      server = http.createServer();

function renderForm(posts, res) {
  const data = ejs.render(template, {
      posts: posts
  });
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(data);
  res.end();
}

function insertData(query, posts, res) {
  query.date = (new Date()).toLocaleString();
  posts.push(query);
  renderForm(posts, res);
}

server.on('request', (req, res) => {
  const u = url.parse(req.url, true);
  if (u.pathname == '/send') {
    if (req.method == 'POST') {
      let data = "";
      req.on('data', x => data += x);
      req.on('end', () => insertData(qs.parse(data), posts, res));
    } else {
      insertData(u.query, posts, res);
    }
  } else {
    renderForm(posts, res);
  }
});
server.listen(1337, 'localhost');
console.log("server listening...");