from bs4 import BeautifulSoup
from markdown import markdown
from flask import Flask
from flask_restful import Api, Resource, reqparse
from flask_cors import CORS
import random
import os

class Post(Resource):

    def get(self, slug=""):

        path = "./posts"
        files = os.listdir(path)

        # general file name format will be:
        # <iso date>_<category>_<slug>.md
        # eg 2021-06-02_projects_my-kubernetes-cluster.md

        if slug == "":
            _file = random.choice(files)
            tokens = _file.split('_')

            _date = tokens[0]
            _category = tokens[1]
            _title = tokens[2].replace('.md', '')
            _slug = _title.lower().replace(' ', '-')

            _post = {
                "slug": _slug,
                "title": _title,
                "date": _date,
                "category": _category,
                "content": render(open(path+'/'+_file, 'r').read())
            }
            return _post, 200

        for _file in files:
            tokens = _file.split('_')

            _date = tokens[0]
            _category = tokens[1]
            _title = tokens[2].replace('.md', '')
            _slug = _title.lower().replace(' ', '-')

            if(_slug == slug):
                _post = {
                    "slug": _slug,
                    "title": _title,
                    "date": _date,
                    "category": _category,
                    "content": render(open(path+'/'+_file, 'r').read())
                }
                return _post, 200

        return "Post not found", 404

class Posts(Resource):

    def get(self, slug=""):

        path = "./posts"
        files = os.listdir(path)
        posts = []

        # general file name format will be:
        # <iso date>_<category>_<slug>.md
        # eg 2021-06-02_projects_my-kubernetes-cluster.md

        for _file in files:
            tokens = _file.split('_')

            _date = tokens[0]
            _category = tokens[1]
            _title = tokens[2].replace('.md', '')
            _slug = _title.lower().replace(' ', '-')

            _post = {
                "slug": _slug,
                "title": _title,
                "date": _date,
                "category": _category,
                "content": render(open(path+'/'+_file, 'r').read())
            }

            posts.append(_post)
            
        return posts, 200


def render(content):
    """Render Markdown Syntax to final HTML."""
    soup = BeautifulSoup(markdown(content, extensions=['codehilite']), features="html.parser")
    _add_a_attrs(soup)
    return soup.decode()

def _add_a_attrs(soup):
    """Add HTML attrs to our link elements"""
    for tag in soup.find_all("a"):
        tag['rel'] = "nofollow"
        tag['target'] = "_blank"


api = Flask(__name__)
CORS(api)
_api = Api(api)

_api.add_resource(Post, "/post/<string:slug>")
_api.add_resource(Posts, "/posts")
