const {apiServer, axios, cleanEntry} = require('./env');


const get = async (config, opts) => {
  let entry_id;
  let match;
  if  ( match = opts.pathname.match(/\/(\d+)$/) ) {
    entry_id = parseInt(match[1]);
  } else
  if  ( match = opts.pathname.match(/\/(\d+).html$/) ) {
    entry_id = parseInt(match[1]);
  }
  let res = await axios.get(`${apiServer}/api/entry/${entry_id}`);
  let entry = cleanEntry(res.data);
  //console.log('left', entry.left);
  let title = `${entry.title} | BeesNest合同会社`;
  let params = encodeURI(`count=5&thumbnail=yes`);
  res = await axios.get(`${apiServer}/api/entries/?${params}`);
  let related = [];
  for ( let ent of res.data )   {
    if  ( ent.id != entry.id )  {
      related.push(cleanEntry(ent));
    }
  }

	params = encodeURI(`page_name=blog&body=none&thumbnail=yes&count=20`);
	res = await axios.get(`${apiServer}/api/entries?${params}`);
  let entries = res.data;

  res = await axios.get(`${apiServer}/api/tags?full=true`);
  let tagList = res.data;

  return  ({
    filename: '/templates/blog_entry.ejs',
    data: {
      entry: entry,
      title: title,
      related: related,
      entries: entries,
      tags: tagList
    }
  })
}

module.exports = {
    get: get
}

