{% extends "base.html" %}

{% block title %} Post {% endblock %}

{% block page_content %}
    {# Should be the same as iframe.css (.card-body = body) #}
    <style>
        .card-body,.comment-body {
            font-size: 18px;
        }

        {# Normally, the selectors ".card-body img" and ".OT_image" are the same. #}
        .card-body img,.comment-body img {  {# in case users insert <img> by themselves #}
            max-width: 384px;
            max-height: 384px;
        }

        iframe.OT_video {
            max-width: 30vw;
            max-height: 30vh;
        }

        .OT_image:hover {  {# only OT_image has hover effect (is clickable) #}
            cursor: zoom-in;
        }
        .OT_reply {
            padding: 0 5px;
            color: black;
            text-decoration: none;
            border: 1px solid black;
            border-radius: 20px;
            background-color: #c1fce3;
            cursor: pointer;  /* IMPORTANT: only difference is here, because in the editor you cannot click the href */
            font-size: 16px;
        }
        .OT_reply:hover {
            color: #444444;
            background-color: #98fcd1;
        }
        /* Bootstrap overwrite */
        .btn {
            margin-right: 5px;
        }
        .my-float-end {  /* replace float-end */
            display: flex;
            justify-content: flex-end;
            padding-right: -10px;
        }
        /* Other styles */
        .empty-notice {
            margin: 5% auto;
            font-size: 4rem;
            font-family: Georgia, serif;
            font-weight: 200;
            font-style: italic;
            text-align: center;
        }
        .to-board {
            display: flex;
            flex-direction: row;  /* overwrite what is in bootstrap */
            height: 40px;
            margin-bottom: 5px;
        }
        .to-board-item {
            display: flex;
            flex-direction: column;
            justify-content: center;
            margin-left: 10px;
            cursor: pointer;
        }
        .cover {
            width: 30px;
            height: 30px;
            border: 1px solid transparent;
            border-radius: 5px;
        }
        .cover:hover {
            border: 1px solid #c9b4b4;
        }
        .back-to {
            color: #2d64b3;
        }
        .back-to:hover {
            text-decoration: underline;
        }
        .bname {
            font-size: 20px;
            color: #0d6efd;
        }
        .bname:hover {
            color: #0a58ca;
        }
        .floor {
            color: #999;
            font-size: 1rem;
        }
        .main-floor {
            margin-right: 10px;
        }
        .comment-body {
            text-align: justify;
            margin-top: 10px;
            margin-right: 20px;
        }
        .sub-floor {
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            margin-right: 10px;
        }

    </style>
    <div class="card to-board">
        <div class="back-to to-board-item">&lt;Back to {{ data["board_info"]["bname"] }}</div>
{#        <div class="to-board-item"><img class="cover" src="{{ "/cdn/" + data["board_info"]["cover"] }}" alt=""></div>#}
{#        <div class="bname to-board-item">{{ data["board_info"]["bname"] }}</div>#}
    </div>
    <div class="card">
        <div class="card-body">
            <div class="display-1" style="text-align: justify">{{ data['post_info']['title'] }}</div>

            <br>

            <div class="blockquote-footer">{{ moment(data['post_info']['publish_time']).fromNow() }}</div>
            <div style="text-align: right; {% if data['num_page'] <= 1 %}display: none{% endif %}">
                Rank by:
                <a class="text-decoration-none" href="javascript:setParam('order', 'desc')">desc</a>
                <a class="text-decoration-none" href="javascript:setParam('order', 'asc')">asc</a>
                <a class="text-decoration-none" href="javascript:setParam('order', 'like_count')">likes</a>
            </div>
            <div class="float-start">
                <a class="text-decoration-none" target="_blank"
                   href="{{ url_for('abstract_user.get_personal_profile', Uid=data.post_info['Uid']) }}">
                    <img alt="avatar" src="{{ '/cdn/'+ data.post_info["avatar"] }}" width="32" height="32"
                         class="rounded-circle">
                </a>
            </div>
            <div class="lead float-start">
                <a class="text-body text-decoration-none"
                   href="{{ url_for('abstract_user.get_personal_profile', Uid=data.post_info['Uid']) }}">&nbsp;{{ data.post_info['owner'] }}</a>
            </div>
            <br>
            <br>

            <div class="btn-group">
                <button id="plb-{{ data.post_info['Pid'] }}" class="btn like-btn btn-outline-danger {% if data.post_info['liked_by_user'] %}active{% endif %}">
                    <i class="bi bi-hand-thumbs-up"></i>
                    <span id="pl-{{ data.post_info['Pid'] }}"> {{ data.post_info['like_count'] }}</span></button>

                <button id="pdb-{{ data.post_info['Pid'] }}" class="btn dislike-btn btn-outline-dark {% if data.post_info['disliked_by_user'] %}active{% endif %}">
                    <i class="bi bi-hand-thumbs-down"></i>
                    <span id="pd-{{ data.post_info['Pid'] }}"> {{ data.post_info['dislike_count'] }}</span></button>

            </div>
            {# Report post button #}
            <div class="float-end">
                <span class="main-floor floor">#1</span>
                <a class="text-decoration-none text-body"
                   href="{{ url_for('user.report', target='post', id=data.post_info['Pid']) }}">
                    <div class="btn btn-outline-info">Report</div>
                </a>
            </div>

            {% if session['Uid'] and session['Uid'] == data.post_info['Uid'] %}
                {# Delete post trigger #}
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#deletePostModal">
                    Delete Post
                </button>

                {# Delete post modal #}
                <div class="modal fade" id="deletePostModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Delete Post</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                Are you sure you want to delete the post?
                                <br>
                                (All the comments are also deleted!)
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <form action="{{ url_for('api.delete_post') }}" method="post">
                                    <input type="hidden" name="Bid" value="{{ data.post_info['Bid'] }}">
                                    <input type="hidden" name="Pid" value="{{ data.post_info['Pid'] }}">
                                </form>
                                <button class="btn btn-primary p-del-btn" data-pid="{{ data.post_info['Pid'] }}">Delete</button>
                            </div>
                        </div>
                    </div>
                </div>
            {% endif %}

            {# Post content #}
            <hr>

            <p>{{ data['post_info']['content']|safe }}</p>
        </div>
    </div>

    {# Comments #}
    {% if data['comments']|length > 0 %}
        <br>
        <div class="display-6">Comments:</div>
        <br>
    {% else %}
        <p class="empty-notice">Do Not Make the Poster Feel Lonely~</p>
    {% endif %}

    {% for comment in data['comments'] %}
        <div class="card">
            <div class="card-body">
                <div class="card-title">
                    <div class="float-start">
                        <a class="text-body text-decoration-none" target="_blank"
                           href="{{ url_for('abstract_user.get_personal_profile', Uid=comment['Uid']) }}">
                            <img src="{{ '/cdn/'+ comment["user_avatar"] }}" width="32" height="32"
                                 alt="avatar" class="rounded-circle">
                        </a>
                    </div>
                    <a class="text-body text-decoration-none"
                       href="{{ url_for('abstract_user.get_personal_profile', Uid=comment['Uid']) }}">
                        <div class="lead">&nbsp;{{ comment['publish_user'] }}</div>
                    </a>
                </div>
                <div class="blockquote-footer float-end">{{ moment(comment['publish_time']).fromNow() }}</div>
                <div class="card-body">

                    <div class="btn-group">

                        <button id="clb-{{ comment['Cid'] }}" class="btn btn-sm like-btn btn-outline-danger {% if comment['liked_by_user'] %}active{% endif %}">
                            <i class="bi bi-hand-thumbs-up"></i>
                            <span id="cl-{{ comment['Cid'] }}"> {{ comment['like_count'] }}</span>
                        </button>

                        <button id="cdb-{{ comment['Cid'] }}" class="btn btn-sm dislike-btn btn-outline-dark {% if comment['disliked_by_user'] %}active{% endif %}">
                            <i class="bi bi-hand-thumbs-down"></i>
                            <span id="cd-{{ comment['Cid'] }}"> {{ comment['dislike_count'] }}</span>
                        </button>

                    </div>

                    {% if session['Uid'] and session['Uid'] == comment['Uid'] %}
                        {# Delete comment trigger #}
                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                data-bs-target="#deleteCommentModal{{ loop.index }}">
                            Delete
                        </button>

                        {# Delete comment modal #}
                        <div class="modal fade" id="deleteCommentModal{{ loop.index }}" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Delete Comment</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        Are you sure you want to delete the comment?
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel
                                        </button>
                                        <form action="{{ url_for('api.delete_comment') }}" method="post">
                                            <input type="hidden" name="Cid" value="{{ comment['Cid'] }}">
                                            <input type="hidden" name="Pid" value="{{ data.post_info['Pid'] }}">
                                        </form>
                                        <button class="btn btn-primary c-del-btn" data-cid="{{ comment['Cid'] }}">Delete</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    {% endif %}
                    <br>
                    <div class="comment-body">{{ comment['content']|safe }}</div>
                </div>
                <div class="my-float-end">
                    <div class="sub-floor floor">#{{ comment["floor"] }}</div>
                    {# report button #}
                    <a class="text-decoration-none text-body"
                       href="{{ url_for('user.report', target='comment', id=comment.Cid) }}">
                        <div class="btn btn-sm btn-outline-info">Report</div>
                    </a>
                    {# reply button #}
                    <a class="text-decoration-none text-body" href="#ue-anchor"
                       onclick="insertReply('{{ comment['Uid'] }}', '{{ comment['publish_user'] }}',
                               '{{ comment["floor"] }}', '{{ comment["Cid"] }}');">
                        <div class="btn btn-sm btn-outline-info">Reply</div>
                    </a>
                </div>

            </div>
        </div>
        {% if not loop.last %}
            <br>
        {% endif %}
    {% endfor %}
    <hr>
    {# Add comment #}
    <div class="card">
        <div class="card-body">
            <div>
                <div class="form-group row">
                    <label for="editor" class="col-sm-2 col-form-label">Add Comment</label>
                    <div class="col-sm-10">
                        {# anchor for editor #}
                        <a id="ue-anchor"></a>
                        <script id="editor" type="text/plain" style="width: 100%; height: 200px"></script>
                    </div>
                </div>
                <br>
                <input type="hidden" id="Pid" value="{{ data['post_info']['Pid'] }}">
                <div class="form-group row">
                    <div class="col-sm-10">
                        <button class="btn btn-primary btn-submit">Comment</button>
                        <button id="btn-preview" class="btn btn-primary"
                                onclick="previewComment();">Preview</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <br>
    <script charset="UTF-8" src="{{ url_for("static", filename="/ueditor/ueditor.config.js") }}"></script>
    <script charset="UTF-8" src="{{ url_for("static", filename="/ueditor/ueditor.all.min.js") }}"></script>
    <script charset="UTF-8" src="{{ url_for("static", filename="/ueditor/lang/en/en.js") }}"></script>
    <script>
        var Uid = {{ session["Uid"] or 0 }};
        var Pid = {{ data["post_info"]["Pid"] }};
        var like_btn = $(".like-btn");
        var dislike_btn = $(".dislike-btn");

        // must add css after DOM render, upper place won't work
        like_btn.css("border-radius","5px");
        dislike_btn.css("border-radius","5px");

        // bind back to board events
        $(".to-board-item").on("click", () => {
            location.href = "/board/{{ data["post_info"]["Bid"] }}";
        })
        // set OT_image link
        $(".OT_image").on("click", function () {
            // let cur_index = $(".OT_image").index(this);
            let src = $(this).attr("src");
            window.open("/photos?Pid="+Pid+"&src="+src);  // show images within both the post and comment content
        })
        // prepare ueditor
        var ue = UE.getEditor('editor', {
            toolbars: [["emotion", "simpleupload", "insertimage", "insertvideo", "link", "|", "undo", "redo"]],
            autoHeightEnabled: false,
            enterTag: "br",  // user "br" instead of "p" to escape line
            retainOnlyLabelPasted: true, // remove all attributes of pasted tag
            pasteplain: true,  // paste as plaintext
            imageScaleEnabled: false,
            elementPathEnabled: false,
            wordCount: !!Uid,
            maximumWords: 1000
        });
        ue.ready(() => {
            // get rid of popup messages
            $(".edui-editor-messageholder.edui-default").css({"visibility": "hidden"});

            // lock editor when user not logged-in
            if (!Uid) {
                // disable editor
                ue.setDisabled();

                // add log in display info
                var login_href = "/login?redirect=" + parent.location.href;
                ue.setContent("Please <a href='" + login_href + "' target='_top'>log in</a> to create comment.")

                // disable buttons
                $(".btn-submit").attr("disabled", "disabled");
                $("#btn-preview").attr("disabled", "disabled");
            }

            // disable popup window to modify/clear link
            $(".edui-popup-content").css("display", "none");
        })

        function sendLike(which, target, id) {  // which: like/dislike, 1=like, 0=like
            let url = which ? "/api/like" : "/api/dislike";
            $.ajax({
                method: "POST",
                url: url,
                dataType: "json",
                data: {target: target, id: id},
                success: data => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        let l_b = $("#"+target.substr(0, 1)+"lb-"+id);
                        let d_b = $("#"+target.substr(0, 1)+"db-"+id);
                        let f = (which) ? d_b : l_b;
                        let u = (which) ? l_b : d_b;
                        f.removeClass("active");
                        if (data["cur_status"]) {
                            u.addClass("active");
                        } else {
                            u.removeClass("active");
                        }
                        $("#"+target.substr(0, 1)+"l-"+id).text(" "+data["like_count"]);
                        $("#"+target.substr(0, 1)+"d-"+id).text(" "+data["dislike_count"]);
                    }
                }
            })
        }

        // like/dislike post/comment
        like_btn.on("click", function () {
            let me = this.id;
            sendLike(1, (me.substr(0, 1)==="p")?"post":"comment", me.substring(4, me.length));
        })

        dislike_btn.on("click", function () {
            let me = this.id;
            sendLike(0, (me.substr(0, 1)==="p")?"post":"comment", me.substring(4, me.length));
        })

        $(".btn-submit").on("click", () => {
            // check login status
            if (!Uid) {
                alert("Please log in to create a comment!");
                location.href = "/login";
                return
            }
            // check content not null
            if (!ue.hasContents()) {
                alert("You must enter comment content!");
                return
            }
            // if everything ok, send request
            var Pid = $("#Pid").val();
            $.ajax({
                method: "POST",
                url: "/api/comment/add",
                dataType: "json",
                data: {
                    Pid: Pid,
                    content: ue.getContent().trim(),
                    text: ue.getContentTxt().trim()
                },
                success: data => {
                    if (data.status !== 1) {
                        alert(data.error.msg)
                    } else {
                        location.href = "/post/" + Pid + "?order=desc";
                    }
                }
            })
        })

        function insertReply(uid, uname, floor, cid) {
            if (!Uid) {return}  // do not insert any content if not logged in
            ue.ready(() => {
                // set as new text
                ue.setContent('<p><a class="OT_reply" data-cid="'+ cid + '"' +' data-uid="'+uid+'"'+'href="/profile/' +
                    uid + '" target="_blank">@' + uname + ' (#' + floor + '):</a>&nbsp;</p>')
                ue.focus(true);  // focus cursor at the end of text
            })
        }

        function previewComment() {
            var opener = window.open("", "_blank");
            opener.document.write("<title>Preview Comment</title>");  // window title
            opener.document.write('<link rel="stylesheet" ' +
                'href="{{ url_for('static', filename='ueditor/themes/iframe.css') }}">')  // style same as in iframe.css
            opener.document.write(ue.getContent());  // content
        }
    </script>

    {# Pagination #}
    <nav {% if data['num_page'] <= 1 %}style="display: none"{% endif %}>
        <ul class="pagination justify-content-center">
            <li class="page-item {% if data['page'] == 1 %}disabled{% endif %}">
                <a class="page-link" href="javascript:setParam('page',{{ data['page'] - 1 }})"
                   tabindex="-1">Previous</a>
            </li>

            {% for i in range(1, 1 + data['num_page']) %}
                <li class="page-item{% if i == data['page'] %} active {% endif %}">
                    <a class="page-link" href="javascript:setParam('page',{{ i }})">{{ i }}</a>
                </li>
            {% endfor %}

            <li class="page-item {% if data['page'] == data['num_page'] %}disabled{% endif %}">
                <a class="page-link" href="javascript:setParam('page',{{ data['page'] + 1 }})">Next</a>
            </li>
        </ul>
    </nav>
{% endblock %}


{% block scripts %}
    {{ super() }}
    <script>
        $(".p-del-btn").on("click", function () {
            let Pid = $(this).data("pid");
            $.ajax({
                method: "POST",
                url: "/api/post/delete",
                dataType: "json",
                data: {Pid: Pid},
                success: data => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        location.href = "/board/" + "{{ data.post_info['Bid'] }}";
                    }
                }
            })
        })

        $(".c-del-btn").on("click", function () {
            let Cid = $(this).data("cid");
            $.ajax({
                method: "POST",
                url: "/api/comment/delete",
                dataType: "json",
                data: {Cid: Cid},
                success: data => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        location.href = "/post/" + "{{ data.post_info['Pid'] }}" + "?order=desc";
                    }
                }
            })
        })
    </script>
{% endblock %}
