class BlogIndex extends HTMLElement {
    constructor() {
        super();
        this.getBlogPosts();
    }

    async getBlogPosts() {
        var graphql = JSON.stringify({
        query: 'query($count: Int! $contentLength: Int!) { blogPosts(count: $count contentLength: $contentLength) { content title id }}',
        variables: {
            "count": 3,
            "contentLength": 300
        }
        })
        var requestOptions = {
        method: 'POST',
        body: graphql,
        headers: { 'Content-Type': 'application/json' }
        };
        let posts = (await (await fetch("/API/graphql.php", requestOptions)).json()).data.blogPosts;
        posts.forEach((element) => {
            const article = document.createElement("article");
            article.classList.add("breakWord");
            this.appendChild(article);

            const h2 = document.createElement("h2");
            h2.innerText = element["title"];
            article.appendChild(h2);

            const content = document.createElement("p");
            content.classList.add("breakWord");
            content.innerHTML = element["content"];
            article.appendChild(content);

            const moreP = document.createElement("p");
            moreP.classList.add("center");
            article.appendChild(moreP);

            const moreLink = document.createElement("a");
            moreLink.href = "/post.html?id=" + element["id"];
            moreP.appendChild(moreLink);

            const moreButton = document.createElement("button");
            moreButton.innerText = "Mehr lesen";
            moreLink.appendChild(moreButton);
        });
    }
}

customElements.define("jl-blog_index", BlogIndex);
