let converter = new showdown.Converter({
    parseImgDimensions: true,
    headerLevelStart: 3,
    extensions: ["prettify"]
});
$.ajax({
    dataType: "json",
    url: "blog/posts.json",
    cache: false,
    success: function (json) {
        let list = $('#blog-list');
        list.html("");
        for (let i = json.length - 1; i >= 0; i--) {
            var obj = json[i];
            let id = obj["id"];

            let p = "";
            p += '<a class="blog-anchor" id="blog-' + id + '"></a>';
            p += '<div class="card bg-light blog-entry rounded-0">';
            p += '<div class="card-body">';
            p += '<a class="blog-button" id="blog-button-' + id + '"><h2 class="card-title">' + obj["name"] + '</h2></a>';
            p += '<div class="card-text text-muted blog-summary" id="blog-summary-' + id + '">' + obj["summary"] + '</div>';
            p += '<div class="card-text" id="blog-post-' + id + '"></div>';
            p += '<span class="text-muted project-status">' + obj["date"] + "</span>";
            var discussLink = obj["discuss"];
            if (discussLink)
                p += '<a href="' + discussLink + '" class="blog-discuss" id="blog-discuss-' + id + '"></a>'
            p += '</div></div>';
            list.append(p);

            $("#blog-button-" + id).on('click', function () {
                var post = $("#blog-post-" + id);
                if (post.html() !== "") {
                    post.html("");
                    var discuss = $("#blog-discuss-" + id);
                    if (discuss.length)
                        discuss.html("");
                    $("#blog-summary-" + id).show();
                    history.pushState(null, null, "#blog");
                } else {
                    openBlogPost(id);
                    history.pushState(null, null, "#blog-" + id);
                }
            });
        }

        if (window.location.hash.startsWith("#blog-")) {
            var anchor = $(window.location.hash);
            if (anchor.length) {
                openBlogPost(window.location.hash.substring(6), function () {
                    $('html, body').animate({
                        scrollTop: anchor.offset().top
                    }, 0)
                });
            }
        }
    }
});

function openBlogPost(id, onDone) {
    $.get("blog/" + id + ".md", function (markdown) {
        let html = converter.makeHtml(markdown);
        $("#blog-post-" + id).html(html);

        var discuss = $("#blog-discuss-" + id);
        if (discuss.length)
            discuss.html("Discuss this post");
        $("#blog-summary-" + id).hide();

        PR.prettyPrint();
        if (onDone)
            onDone();
    });
}