const axios = require('/home/wasp/cms_v3/node_modules/axios');
const {cleanEntry} = require('/home/wasp/cms_v3/libs/entry');

const apiServer = 'https://api.wasp.co.jp';
//const apiServer = 'http://localhost:3011';

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} | WASP株式会社`;
    let params;
    if ( entry.category )   {
        params = encodeURI(`count=5&category=${entry.category.name}&thumbnail=yes`);
    } else {
        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/categories`);
	let categories = res.data;

  let category = null;
  if ( entry.category){
    res = await axios.get(`${apiServer}/api/categories/${entry.categoryId}`);
    category = res.data;
  }

    return  ({
        filename: '/templates/blog_entry2.ejs',
        data: {
            entry: entry,
            title: title,
            related: related,
            entries: entries,
            categories: categories,
            category: category
        }
    })
}

module.exports = {
    get: get
}

