{% extends "base.html" %}

{% block title %} Boards {% endblock %}

{% block page_content %}
    <style>
        .preview {
            max-height: 15vmax;
            max-width: 15vmax;
        }
        .preview-img:hover {
            cursor: zoom-in;
        }
        /* Bootstrap overwrite */
        .btn {
            margin-right: 5px;
        }
        /* Other styles */
        .empty-notice {
            margin: 5% auto;
            font-size: 4rem;
            font-family: Georgia, serif;
            font-weight: 200;
            font-style: italic;
            text-align: center;
        }
        .body {
            padding-top: 10px;
            max-height: 8vmax;
            max-width: 60vw;
            overflow: hidden;
            text-align: justify;
        }
        .post-wrap {
            display: flex;
            justify-content: space-between;
            background-color: #ffffff;
            padding: 15px 10px;
            border: 1px solid #d1d2d4;
            margin-bottom: 15px;
        }
        .post-wrap:hover {
            background-color: #edeff2;
        }
        .post-title {
            display: inline-block;
            max-width: 55vw;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        .word-count {
            text-align: right;
            font-size: 0.9rem;
            color: #aaa;
        }
        .board-header {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .board-info {
            width: 100%;
            display: flex;
            flex-direction: row;
        }
        .cover-wrap {  /* center the cover */
            width: 110px;
            height: 110px;
            background-color: white;
            border: 1px solid #DADCDF;
        }
        .board-cover {
            width: 100px;
            height: 100px;

            position: relative;
            top: 4px;  /* beware of border length */
            left: 4px;
        }
        .board-des {
            width: 70%;
            margin-top: 30px;
            font-family: "Noto Sans", Arial, sans-serif;
            font-size: 1rem;
            line-height: 1.4rem;
            word-wrap: break-word;
            text-align: justify;
        }
        .after-cover {
            height: 110px;
            margin-left: 1vw;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .board-name {
            margin-top: 5px;
            font-size: 50px;
            display: flex;
            justify-content: flex-end;
            flex-direction: column;
            text-align: left;
            line-height: 50px;  /* set as font-size to make text touch bottom */
        }
        .subs-wrap {
            height: 50px;
            display: flex;
            align-items: flex-end;
            margin-bottom: 2px;
        }
        .subs-btn {
            height: 30px;
            width: 80px;
            border-radius: 5px;
            margin-left: 2px;  /* compensate for the border */

            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            cursor: pointer;
        }
        .unsub-btn {
            border: 2px solid black;
            background-color: white;
            color: black;
        }
        .unsub-btn:hover {
            background-color: whitesmoke;
        }
        .sub-btn {
            border: 2px solid transparent;
            background-color: #ea0027;
            color: white;
        }
        .sub-btn:hover {
            background-color: red;
        }
        .text-label {
            margin-left: 20px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            color: #aaa;
            font-size: 90%;
        }
        .text-num {
            margin-left: 10px;
            color: #ff7f3e;
            font-size: 90%;
        }
    </style>
    <div class="board-header">
        <div class="board-info">
            <div class="cover-wrap"><img class="board-cover" src="{{ "/cdn/"+data["board_info"]["cover"] }}"
                                         alt=""></div>
            <div class="after-cover">
                <div class="board-name">{{ data['board_info']['name'] }}</div>
                <div class="subs-wrap">
                    {% if data["board_info"]["subs_by_user"] %}
                        <div class="subs-btn unsub-btn">Joined</div>
                        <div class="subs-btn sub-btn" style="display: none">Join</div>
                    {% else %}
                        <div class="subs-btn unsub-btn" style="display: none">Joined</div>
                        <div class="subs-btn sub-btn">Join</div>
                    {% endif %}
                    <div class="text-label">Subscribers:</div>
                    <div class="text-num">{{ data["board_info"]["subs_count"] }}</div>
                </div>
            </div>
        </div>
        <div class="board-des">Desription: {{ data["board_info"]["description"] }}</div>
    </div>
    <br>
    <br>
    <div style="text-align: right">
        Sort by:
        <a class="text-decoration-none" href="javascript:setParam('order', 'latest_comment')">latest comment</a>
        <a class="text-decoration-none" href="javascript:setParam('order', 'newest')">newest</a>
        <a class="text-decoration-none" href="javascript:setParam('order', 'like_count')">likes</a>
    </div>
    <hr>
    {% if data['posts'] | length <= 0  %}
    <p class="empty-notice">Be the First to Post~</p>
    {% endif %}

    {% for post in data['posts'] %}
        <div class="post-wrap">
            <article class="post">
            <header>
                <div>
                    <h3><a href="/post/{{ post['Pid'] }}" class="text-decoration-none post-title">
                        {{ post['title'] }}</a></h3>

                    <div class="blockquote-footer">{{ moment(post['publish_time']).fromNow() }}</div>

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

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

                        <button class="btn btn-sm btn-outline-info disabled" style="margin-left: 10px;border-radius: 0">
                            <i class="bi bi-chat-left-text"></i>&nbsp;&nbsp;{{ post["max_floor"] - 1}}</button>
                    </div>

                </div>
            </header>
            <p class="body">{{ post['summary'] }}</p>
        </article>
            {% if post["preview_type"] == "photo" %}
                <img class="preview-img preview" data-Pid="{{ post['Pid'] }}" alt=""
                     src="{{ "/cdn/" + post["preview_type"] + "/" + post["preview_src"] }}">
            {% elif post["preview_type"] == "video" %}
                <iframe allowfullscreen class="preview-video preview" src="{{ "/play?src=" + post["preview_type"]
                + "/" + post["preview_src"] }}"></iframe>
            {% endif %}
        </div>

    {% endfor %}

    <hr>

    {# Add post #}
    <div>
        <div class="form-group row">
            <label class="col-sm-2 col-form-label" for="title">Title</label>
            <div class="col-sm-10">
                <input class="form-control" name="title" id="title" placeholder="Title" required>
            </div>
            <div class="word-count">0/150</div>
        </div>
        <br>
        <div class="form-group row">
            <label for="editor" class="col-sm-2 col-form-label">Content</label>
            <div class="col-sm-10">
                <script id="editor" type="text/plain" style="width: 100%; height: 300px"></script>
            </div>
        </div>
        <br>
        <input type="hidden" id="Bid" value="{{ data['board_info']['Bid'] }}">
        <div class="form-group row">
            <div class="col-sm-10">
                <button class="btn btn-primary btn-submit">Add Post</button>
                <button id="btn-preview" class="btn btn-primary"
                        onclick="previewPost();">Preview</button>
            </div>
        </div>
    </div>
    <br>

    {# 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>

    <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 title_input = $("#title");
        var w_c = $(".word-count");
        var sub_btn = $(".sub-btn");
        var unsub_btn = $(".unsub-btn");
        var redirect_href = "/login?redirect=" + location.href;
        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");

        // 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: 2000
        });
        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 title
                title_input.attr("disabled", "disabled").attr("placeholder", "You must log in to create a post!");

                // 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");
        })

        // set preview-img link
        $(".preview-img").on("click", function () {
            let Pid = this.getAttribute("data-Pid");
            window.open("/photos?Pid="+Pid);  // show images within the post content
        })

        // monitor title word count
        title_input.on("keyup", function () {
            let count = $(this).val().length;
            let is_exceed = count > 150;
            w_c.text((is_exceed?"Title length exceeded! ":"")+count+"/150").css("color", is_exceed?"#d00303":"#aaa");
        })

        function sendSub(action) {  // action: sub/unsub, 1=sub, 0=unsub
            let hide_btn = action ? sub_btn: unsub_btn;
            let show_btn = action ? unsub_btn: sub_btn;
            $.ajax({
                method: "POST",
                url: "/api/subscribe",
                dataType: "json",
                data: {Bid: {{ data['board_info']["Bid"] }}, action: action},
                success: (data) => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        hide_btn.css("display", "none");
                        show_btn.css("display", "inline");
                        alert(action ? "You are the No."+data.subs_count+" subscriber of this board!"
                            :"Unsubscribe successful!");
                        $(".text-num").text(data.subs_count);
                    }
                }
            })
        }

        // unsubscribe button events
        unsub_btn.on("mouseenter", function () {
            $(this).text("Leave");
        }).on("mouseleave", function () {
            $(this).text("Joined");
        }).on("click", function () {
            if (!Uid) {
                location.href = redirect_href;
            }
            sendSub(0);
        })

        // subscribe button events
        sub_btn.on("mouseenter", function () {
            $(this).text("Now!");
        }).on("mouseleave", function () {
            $(this).text("Join");
        }).on("click", function () {
            if (!Uid) {
                location.href = redirect_href;
            }
            sendSub(1);
        })

        function sendLike(which, target, id) {  // which: like/dislike, 1=like, 0=dislike
            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
        like_btn.on("click", function () {
            let me = this.id;  // plb-xxx
            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));
        })

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

        function previewPost() {
            let opener = window.open("", "_blank");
            opener.document.write("<title>Preview Post</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('<p style="font-size: 2rem">' + title_input.val() + '</p>')  // title
            opener.document.write('<div style="height: 0; width: 100%; border-top: 2px dashed black">' +
                '</div>')  // a separate line
            opener.document.writeln(ue.getContent());  // content
        }
    </script>

{% endblock %}
