import koaRouter from 'koa-router';
import fs from 'fs';
import path from 'path'
import readline from 'readline';
import markdownIt from 'markdown-it';

const router = koaRouter({prefix: '/api/posts'});

function readPostFile(postFilePath) {
    return function(done) {
        var postData = { content: "" };
        var headerCounter = 0;

        var lineReader = readline.createInterface({
            input: fs.createReadStream(postFilePath)
        });

        lineReader.on('line', function(line){
            if(line === "---") {
                headerCounter++;
            } else if(headerCounter == 1) {
                let headerComponents = line.split(':', 2);
                postData[headerComponents[0]] = headerComponents[1].trim();
            } else if(headerCounter == 2 && line.trim() !== "") {
                postData.content += (line + "<br/>");
            }
        });

        lineReader.on('close', function(){
            done(null, postData);
        });
    }
}

router.get('/', function*(next) {
    const postsBaseDir = path.resolve(__dirname, '../../../posts');
    const posts = fs.readdirSync(postsBaseDir);
    var postsData = [];
    let md = markdownIt({html: true, typographer: true});

    for (let i = 0, len = posts.length; i < len; i++) {
        let postFilename = posts[i];
        const postFilePath = path.resolve(postsBaseDir, postFilename);
        let postData = yield readPostFile(postFilePath);

        postData.renderedContent = md.render(postData.content);
        delete postData.content;

        postsData.push(postData);
    }

    this.body = postsData;
});

export default router.middleware();
@@ -788,30 +788,8 @@
 == 2
- && line.trim() !== %22%22
 ) %7B%0A
@@ -1117,16 +1117,480 @@
 seDir);%0A
+    const POSTS_PAGE_SIZE = parseInt(process.env.POSTS_PAGE_SIZE);%0A%0A    let offset = this.request.query.offset ? this.request.query.offset : 1;%0A    if(offset %3E posts.length) %7B%0A        offset = posts.length - POSTS_PAGE_SIZE%0A    %7D%0A%0A    console.log(%22limit1%22, offset + POSTS_PAGE_SIZE);%0A%0A    let limit = (offset + POSTS_PAGE_SIZE - 1) %3E posts.length ? posts.length : offset + POSTS_PAGE_SIZE - 1;%0A%0A    console.log(%22offset%22, offset);%0A    console.log(%22limit%22, limit);%0A%0A
     var 
@@ -1639,27 +1639,8 @@
 tml:
- true, typographer:
  tru
@@ -1666,38 +1666,29 @@
 i = 
-0, len = posts.length
+offset - 1
 ; i %3C l
-en
+imit
 ; i+
@@ -1800,16 +1800,17 @@
 ename);%0A
+%0A
         

Update small issue typos.