'use strict';

import Koa from 'koa';
import 'babel-polyfill';
import Octokat from 'octokat';
import Router from 'koa-router';
import marked from 'marked';

const app = Koa();
const router = Router();
const octo = new Octokat();
const repo = octo.repos('japacible', 'Hackathon-Calendar');
const port = (process.env.PORT || 5000);

app
  .use(router.routes())
  .use(router.allowedMethods());

function getHackathonsFrom(markdown) {
  let tokens = marked.lexer(markdown);
  let hackathons = [];
  for (let key of Object.keys(tokens)) {
    if (tokens[key]['type'] === 'table') {
      let year = tokens[key]['header'][tokens[key]['header'].length - 1];
      hackathons.push.apply(hackathons, tokens[key]['cells']);
      for (let hackathon of hackathons) {
        hackathon.push(year);
      }
    }
  }
  return hackathons;
}

router
  .get('/', function *(next) {
    let message = `An API list of hackathons from
    https://github.com/japacible/Hackathon-Calendar

Endpoints:

- [/upcoming](/upcoming) | get a list of upcoming hackathons

- [/past](/past) | get a list of past hackathons

- [/ping](/ping) | Pong`;
    this.body = marked(message);
  })
  .get('/ping', function *(next) {
    this.body = 'PONG';
  })
  .get('/upcoming',function *(next) {
    this.body = yield repo.contents('README.md').read()
      .then((contents) => {
        return getHackathonsFrom(contents);
      });
  })
  .get('/past',function *(next) {
    this.body = yield repo.contents('Past-Hackathons.md').read()
      .then((contents) => {
        return getHackathonsFrom(contents);
      });
  });

app.listen(port);

@@ -817,18 +817,368 @@
 ckathons
+.map((hackathon) =%3E %7B%0A    let name = hackathon%5B0%5D.match(/%5C%5B(%5B%5E%5C)%5D+)%5C%5D/i)%5B1%5D;%0A    let url = hackathon%5B0%5D.match(/%5C((%5B%5E%5C)%5D+)%5C)/i)%5B1%5D;%0A    let location = hackathon%5B1%5D;%0A    let date = %60$%7Bhackathon%5B2%5D%7D, $%7Bhackathon%5B3%5D.match(/%5C((%5B%5E%5C)%5D+)%5C)/i)%5B1%5D%7D%60;%0A    return %7B%0A      %22name%22: name,%0A      %22url%22: url,%0A      %22location%22: location,%0A      %22date%22: date%0A    %7D;%0A  %7D)
 ;%0A
-
 %7D%0A%0Aroute
@@ -1584,16 +1584,17 @@
 coming',
+ 
 function
@@ -1739,32 +1739,32 @@
 %0A      %7D);%0A  %7D)%0A
-
   .get('/past',f
@@ -1762,16 +1762,17 @@
 '/past',
+ 
 function

Format response in key-value format