var express = require('express');
var router = express.Router();
var Models = require('../../models');
var config    = require('../../../config.json');
router.get('/', function(req, res) {
  res.redirect('/blog/page/1');
});

router.get('/page/:page_num?', function (req, res) {
    var page_num = req.params.page_num;
    var pageNum = page_num;
    if (page_num == null)
        pageNum = 1
    Models.Post.findAll({
        order: [['id', 'DESC']]
    }).then(function (post) {
        //console.log("num: "+pageNum);
        //real page count
        var count = Math.floor(post.length / 6);
        var pageItems = [];
        var itemLimit = 6;
        var rangeStart = (pageNum * itemLimit) - itemLimit;
        //console.log("RANGE START "+rangeStart);
        for (var i = 0; i < itemLimit; i++) {
            try {
                if (post[i + rangeStart].id != null) {
                    pageItems.push(post[i + rangeStart]);
                }
            } catch (e) {
                //console.log(e)
            }
        }
        //console.log("items count: "+pageItems.length)
        res.render(config.theme+'/blog', {
            theme: config.theme,
            title: 'The Twelfth House | Thoughts and Such',
            page_index: pageNum,
            page_count: Math.round(post.length / 6),
            items: pageItems,
            mode: 'blog'
        });
    }).then(function (value) {
        //console.log(value);
    }).catch(function (err) {
        console.log(err);
    })
});

router.get('/:id', function(req, res) {
  Models.Post.findOne({where:{slug: req.params.id}}).then((post) => {
      console.log(post.feature_image)
        
    
    res.render(config.theme+'/blog-post', {
        theme: config.theme,
        title: post.title,
        entry: post.entry_html,
        feature_image: JSON.parse(post.feature_image),
        mode:'blog'
    });

  }).catch((err) => {
      console.log(err);
  });
});


module.exports = router;
