/**
 * File which renders the edit form for the posts and processes
 * the post data generated by edit forms.
 *
 * @type {Promise|*}
 */

//parses the post data
const qs = require('querystring');

//updates db
const sql = require('../../utils/sql');


/**
 * Displays a single row in the posts view
 *
 * @param post
 */
const renderPostRow = function(post)
{
    return "<tr>" +
        "<td>" + post.category_id + "</td>" +
        "<td>" + post.name + "</td>" +
        "<td>" + post.picture_url + "</td>" +
        "<td>" + post.published + "</td>" +
        "<td><form action=\"/admin\" method =\"post\" >\n" +
            "<input type=\"submit\" name=\"submit\" value=\"Edit\"\n" +
            "              class=\"btn btn-secondary\"/>\n" +
            "<input type='hidden' name='edit_post' value='" + post.post_id + "'/>"+
            "</form></td>" +
        "</tr>";
};


/**
 * Displays all the posts in a table
 */
const postsTable = function()
{
    const html = "<div class='blogPost p-2'>" +
        "<h1 class=\"text-center\">Posts</h1>" +
        "<div class=\"\"><table class=\"table table-striped\">" +
        "<thead class=\"thead-dark\"><tr>" +
        "<td>Category #</td><td>Name</td><td>Header Picture</td><td>Date</td><td>Edit</td>" +
        "</tr></thead><tbody>";
    return new Promise(function(resolve, reject)
    {
        sql.getAllPosts().then(function(posts)
        {
            var postPromises = [];
            posts.forEach(function(post)
            {
                postPromises.push(renderPostRow(post));
            });

            Promise.all(postPromises).then(function(htmls)
            {
                resolve(html + htmls.join('') + "</tbody></table></div></div><br>");
            }).catch(function(error)
            {
                reject(error);
            });
        }).catch(function(error)
        {
            reject(error);
        })
    });
};


/**
 * Displays the edit form for edit posts
 *
 * @param post_id
 */
const displayRenderForm = function(post_id)
{
    return new Promise(function(resolve, reject)
    {
        sql.getPostById(post_id).then(function(post)
        {
            const html = "<div class='blogPost'>"+
                "<h1 class=\"text-center\">Edit Post</h1>"+
                "<form action=\"/admin\" method =\"post\" >"+
                "    <div class=\"form-group\">\n" +
                "        <input class=\"form-control\" type=\"text\" name=\"edit_cat_num\" value='" + post.category_id + "' required>\n" +
                "        <label class=\"w3-label w3-validate\">Category Number</label>\n" +
                "    </div>"+
                "    <div class=\"form-group\">\n" +
                "        <input class=\"form-control\" type=\"text\" name=\"edit_name_new\" value='" + post.name + "' required>\n" +
                "        <label class=\"w3-label w3-validate\">Post Title</label>\n" +
                "    </div>"+
                "    <div class=\"form-group\">\n" +
                "        <input class=\"form-control\" type=\"text\" name=\"edit_pic\" value='" + post.picture_url + "' required>\n" +
                "        <label class=\"w3-label w3-validate\">Picture URL</label>\n" +
                "    </div>"+
                "    <div class=\"form-group\">\n" +
                "        <input class=\"form-control\" type=\"date\" name=\"edit_date\" value='" + post.published.toISOString().split('T')[0] + "' required>\n" +
                "        <label class=\"w3-label w3-validate\">Published Date</label>\n" +
                "    </div>"+
                "    <div><input type=\"submit\" name=\"submit\" value=\"Edit\"\n" +
                "              class=\"btn btn-lg btn-secondary\"/></div>"+
                "<input type='hidden' name='edit_post_2' value='" + post_id + "'/>"+
                "</form>"+
                "</div><br>";

            resolve(html);
        }).catch(function(error)
        {
            reject(error);
        });

    });
};


/**
 * Detects if the post data came from the edit form in posts table or edit post
 * in the edit post form. Based on this, this function will call one of two functions
 *
 * @param postData
 */
const processPost = function(postData)
{
    return new Promise(function(resolve, reject)
    {
        var postParsed = qs.parse(postData);

        if(postParsed.edit_post)
        {
            //display edit form
            displayRenderForm(postParsed.edit_post).then(function(html)
            {
                resolve(html);
            }).catch(function(error)
            {
                reject(error);
            });
        }
        else if(postParsed.edit_post_2)
        {
            sql.editPost(postParsed).then(function(html)
            {
                resolve(html);
            }).catch(function(error)
            {
                reject(error);
            });
        }
        else
        {
            resolve("");
        }
    });
};


module.exports=
{
    /**
     * Method which calls helper functions which processes post data for editing posts
     * and calls a function which displays all the posts in a table
     *
     * @param postData
     */
    main: function(postData)
    {
        return new Promise(function(resolve, reject)
        {
            Promise.all([processPost(postData),
                postsTable()]).then(function(html)
            {
                resolve("<br>" + html.join(''));
            }).catch(function(error)
            {
                console.log("error in edit post.js");
                reject(error);
            })
        });
    }
};