{% extends "base.html" %}

{% block title %} Profile {% endblock %}

{% block page_content %}
    <style>
        #avatar-upload {
            margin-top: 4px;
        }
        #view-origin {
            margin-left: 2vw;
            position: relative;
            bottom: -20px;
        }
        /* status box */
        .status-wrapper {
            display: flex;
            justify-content: space-around;
            height: 15vmin;
            width: 100%;
        }
        .sep-line {
            width: 0;
            height: 100%;
            border-left: 1px solid #7b7b7b;
        }
        .status-box {
            width: 25%;
            height: 15vmin;
            text-align: center;
            cursor: pointer;
            transition: background-color 0.3s ease-out;
        }
        .status-box:hover {
            background-color: #eeeeee;
        }
        .status-des {
            color: #171A21;
            font-family: Geneva, sans-serif;
            font-size: 4vmin;
            font-weight: bold;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .status-num {
            color: #171A21;
            font-size: 3.5vmin;
        }
    </style>
    <div class="display-6">{{ data['nickname'] }}</div>
    <hr>
    {% if data['banned'] == 1 %}
        {% if data['isCurrent'] %}
            <div class="alert-danger">You are banned until: {{ data['banDuration'] }}</div>
        {% else %}
            <div class="alert-danger">User currently banned.</div>
        {% endif %}
    {% endif %}
    <div class="avatar-wrapper">
        {% if data['isCurrent'] %}
        <h4>Change your Avatar</h4>
        <img id="avatar-upload" style=" cursor: pointer" src="{{ '/cdn/'+ session.user_info["avatar"] }}" width="100"
             height="100" class="rounded-circle" data-toggle="tooltip" title="Change your avatar" alt="">
        <input id="uploadImg" type="file" accept="image/*" onchange="uploadImg(this.files[0]);" style="display: none">
        {% else %}
            <img id="avatar-upload" src="{{ '/cdn/'+ data["avatar"] }}" width="100"
                 height="100" class="rounded-circle" alt="">
        {% endif %}
        <div class="btn btn-primary" id="view-origin">View Original</div>
    </div>
    <hr>
    <div class="status-wrapper">
        <div class="status-box">
            <p class="status-des">  <!-- index 0 -->
                {% if data["isCurrent"] %}My Posts{% else %}Posts{% endif %}
            </p>
            <p class="status-num">{{ data["post_count"] }}</p>
        </div>
        <div class="sep-line"></div>
        <div class="status-box">  <!-- index 2 -->
            <p class="status-des">
                {% if data["isCurrent"] %}My Comments{% else %}Comments{% endif %}
            </p>
            <p class="status-num">{{ data["comment_count"] }}</p>
        </div>
        <div class="sep-line"></div>
        <div class="status-box">  <!-- index 4 -->
            <p class="status-des">Subscriptions</p>
            <p class="status-num">{{ data["subs_count"] }}</p>
        </div>
        <div class="sep-line"></div>
        <div class="status-box">  <!-- index 6 -->
            <p class="status-des">Browse History</p>
            <p class="status-num">{{ data["history_count"] }}</p>
        </div>
    </div>
    <hr>
    <div class="h3">
        Date of Birth:
        {{ 'Not Set' if data['dateOfBirth'] is none else moment(data['dateOfBirth']).format('YYYY/M/D') }}
    </div>
    <div class="h3">Gender: {{ 'Not Set' if data['gender'] is none else data['gender'] }}</div>
    <div class="h3">Email Address: {{ 'Not Set' if data['email'] is none else data['email'] }}</div>
    <div class="h3">Phone Number: {{ 'Not Set' if data['phoneNumber'] is none else data['phoneNumber'] }}</div>
    <div class="h3">Address: {{ 'Not Set' if data['address'] is none else data['address'] }}</div>
    <hr>
    {# Modal trigger for change profile #}
    {% if data['isCurrent'] %}
        <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#changeProfileModal">
            Edit profile
        </button>
    {% endif %}

    {# Modal window for change profile #}
    <div class="modal fade" id="changeProfileModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="changeProfileLabel">Change profile</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form action="{{ url_for('api.add_personal_info') }}" method="post">
                        <div class="mb-3">
                            <label for="nickname" class="col-form-label">nickname</label>
                            <input type="text" class="form-control" id="nickname" name="nickname"
                                   value="{{ data['nickname'] }}">
                        </div>
                        <div class="mb-3">
                            <label for="dateOfBirth" class="col-form-label">Date of Birth:</label>
                            <input type="date" class="form-control" id="dateOfBirth" name="date_of_birth">
                        </div>
                        <div class="mb-3">
                            <label for="gender" class="col-form-label">Gender</label>
                            <select id="gender" name="gender" class="form-select">
                                <option selected disabled value="">{{ 'Not set' if data['gender'] is none }}</option>
                                <option value="male">Male</option>
                                <option value="female">Female</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="email" class="col-form-label">Email</label>
                            <input id="email" class="form-control" name="email" type="email"
                                   placeholder="{{ 'john@example.com' if data['email'] is none }}">
                        </div>
                        <div class="mb-3">
                            <label for="phone" class="col-form-label">Phone number</label>
                            <input type="tel" id="phone" class="form-control" name="phone_number"
                                   placeholder="123456789"
                                   value="{{ '' if data['phoneNumber'] is none else data['phoneNumber'] }}">
                        </div>
                        <div class="mb-3">
                            <label for="address" class="col-form-label">Address</label>
                            <label>
                                <input type="text" class="form-control" name="address" placeholder="Address"
                                       value="{{ '' if data['address'] is none else data['address'] }}">
                            </label>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save change</button>
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>
    <style>
        .pop-up {
            display: none;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);

            position: fixed;
            top: 0;
            left: 0;

        }
        /* all wrapper */
        .list-wrapper {
            display: none;
            height: 42vmax;
            z-index: 10;

            position: relative;
            left: calc(50% - 25px - 0px);  /* calc(50% - w1 - l1) */
            top: calc(50% + 40px - 0px);  /* calc(50% + header height - t1) */
            transform: translate(-50%, -50%);
        }
        .post-list-wrapper {
            width: 40vmax;
        }
        .comment-list-wrapper {
            width: 45vmax;
        }
        .subs-list-wrapper {
            width: 35vmax;
        }
        .history-list-wrapper {
            width: 40vmax;
        }
        /* head */
        .head-wrapper {
            display: flex;
            width: 100%;
            height: calc(25px + 10px);  /* h1 + x2 (x2 is the top margin you want for list-wrapper) */
        }
        .list-des {
            width: calc(100% - 25px - 10px - 0px);  /* calc(100% - w1 - x1 - l1) */
            margin-left: 10px; /* x1 */
        }
        .des-text {
            display: flex;
            flex-direction: column;
            justify-content: center;
            font-size: 25px;
            text-align: center;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            min-width: 50px;
            max-width: 90%;
            padding-bottom: 5px;

            position: relative;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        .hide {
            height: 25px;  /* h1 */
            width: 25px;  /* w1 */
            outline: none;
            cursor: pointer;
            color: black;
            background-color: #8e8e8e;
            border: 1px dashed black;
            border-radius: 100%;
            transition: all 0.3s ease-out;
            font-size: 16px;
            text-align: center;
            margin: 0;

            position: relative;
            top: 0;  /* t1 */
            left: 0;  /* l1 */
        }
        .hide:hover {
            border: 1px solid black;
            color: white;
            background-color: #5b5b5b;
            transform: rotate(90deg);
        }
        /* body (list) */
        .content-list {  /* height and width are decided by each one's wrapper */
            position: relative;
            left: calc(25px + 0px + 10px);  /* 25px = w1, 0px = l1, x1 = 10px = left margin you want */
            top: 0;

            border: 1px solid #2f2e2e;
            border-radius: 10px;
            background-color: rgb(245, 245, 245);
            width: calc(100% - 25px - 10px - 0px);  /* calc(100% - h1 - x1 - l1) */
            height: calc(100% - 25px - 10px - 0px);  /* calc(100% - h1 - x2 - t1) */

            display: flex;
            justify-content: center;
            align-content: flex-start;
            flex-wrap: wrap;
        }
        .content {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #b8b7b7;
            width: 95%;
            height: 11.5%;  /* (100% - 8%) / 8 */
        }
        /* common class for content */
        .center-nowrap {
            text-align: center;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        .post-title {
            max-width: 80%;
            font-size: 20px;
            font-family: IBMPlexSans, Arial, sans-serif;
            font-weight: bold;
        }
        .post-title:hover {
            text-decoration: underline;
        }
        .board-name {
            font-family: BentonSans, sans-serif;
        }
        .timestamp {
            font-family: BentonSans, sans-serif;
            cursor: default;
            color: #999898;
        }
        /* content: post */
        .post {
            flex-direction: column;
            justify-content: space-around;
        }
        .p-top {
            height: 55%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 2px;
        }
        .p-bottom {
            height: 35%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2px;
        }
        .p-del {
            color: blueviolet;
            text-decoration: underline;
            cursor: pointer;
        }
        /* content: comment */
        .comment {
            flex-direction: column;
            justify-content: space-around;
        }
        .c-top {
            height: 55%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 2px;
        }
        .c-bottom {
            height: 35%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2px;
        }
        .c-text {
            max-width: 80%;
            font-size: 20px;
            font-family: IBMPlexSans, Arial, sans-serif;
            font-weight: bold;
        }
        .c-text:hover {
            text-decoration: underline;
        }
        .c-ptitle {
            font-family: BentonSans, sans-serif;
        }
        /* content: history */
        .history {
            flex-direction: column;
            justify-content: space-around;
        }
        .h-top {
            height: 55%;
            display: flex;
            margin-top: 2px;
        }
        .h-bottom {
            height: 35%;
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }
        .h-bname {
            max-width: 40%;
        }
        .h-time {
            max-width: 25%;
        }
        /* content: subs */
        .subs {
            height: 18.4%;  /* (100% - 8%) / 5 */
            justify-content: space-between;
        }
        .s-left {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-basis: 70%;
        }
        .s-right {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            flex-basis: 20%;
        }
        .s-cover {
            /* content width = 95% * (100% - 35px) * 35vmax, height = 11.5% * (100% - 35px) * 42vmax */
            height: 70%;
            width: 23.4%;
            border-radius: 10px;
            background-color: white;
        }
        .s-bname {
            width: 68%;
            font-size: 20px;
            text-align: justify;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .s-unsub {
            color: red;
            text-decoration: underline;
            cursor: pointer;
        }
        /* foot */
        .foot-wrapper {
            border-bottom: none;
            height: 8%;
            justify-content: space-around;
        }
        .arrow {
            display: flex;
            flex-direction: column;
            justify-content: center;
            cursor: pointer;
            text-align: center;
            font-size: 20px;
        }
        .index {
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            font-size: 20px;
        }
        /* loading */
        .loading {
            display: none;
            width: 100%;
            height: 100%;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            font-size: 4rem;
            font-family: "Courier New", monospace;
        }
        .close-loading {
            background-color: red;
            border-radius: 100%;
            width: 5vmax;
            height: 5vmax;
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            cursor: pointer;

            position: relative;
            left: 50%;
            transform: translateX(-50%);
        }
        /* general class for content */
        .href {
            cursor: pointer;
        }
        /* status class */
        .deleted {  /* status = 1 or 2 */
            color: darkgrey;
        }
    </style>
    <!-- popup (show when click on status box) -->
    <div class="pop-up">
        <div class="loading">Loading...<br>Please wait...<div class="close-loading" onclick="hidePopup()">&times;</div> </div>
        <!-- for posts -->
        <div class="post-list-wrapper list-wrapper">
            <div class="head-wrapper">
                <div class="hide">&#10005</div>
                <div class="list-des"><p class="des-text"></p></div>
            </div>
            <div class="post-list content-list">
                {% for _ in range(8) %}
                <div class="post content">
                    <div class="p-top">
                        <div class="p-title post-title center-nowrap href"></div>
                        {% if session["Uid"] == data["Uid"] %}
                        <div class="p-del"></div>
                        {% endif %}
                    </div>
                    <div class="p-bottom">
                        <div class="p-bname board-name center-nowrap href"></div>
                        <div class="p-time timestamp center-nowrap"></div>
                    </div>
                </div>
                {% endfor %}
                <div class="content foot-wrapper">
                    <div class="prev-arrow arrow">&#9668Prev</div>
                    <div class="index">-/-</div>
                    <div class="next-arrow arrow">Next&#9658</div>
                </div>
            </div>
        </div>
        <!-- for comment -->
        <div class="comment-list-wrapper list-wrapper">
            <div class="head-wrapper">
                <div class="hide">&#10005</div>
                <div class="list-des"><p class="des-text"></p></div>
            </div>
            <div class="comment-list content-list">
                {% for _ in range(8) %}
                <div class="comment content">
                    <div class="c-top">
                        <div class="c-text center-nowrap href"></div>  {# post-title #}
                        {% if session["Uid"] == data["Uid"] %}
                        <div class="c-del"></div>
                        {% endif %}
                    </div>
                    <div class="c-bottom">
                        <div class="c-ptitle center-nowrap href"></div> {# board-name #}
                        <div class="c-time timestamp center-nowrap"></div>
                    </div>
                </div>
                {% endfor %}
                <div class="content foot-wrapper">
                    <div class="prev-arrow arrow">&#9668Prev</div>
                    <div class="index">-/-</div>
                    <div class="next-arrow arrow">Next&#9658</div>
                </div>
            </div>
        </div>
        <!-- for subs -->
        <div class="subs-list-wrapper list-wrapper">
            <div class="head-wrapper">
                <div class="hide">&#10005</div>
                <div class="list-des"><p class="des-text"></p></div>
            </div>
            <div class="subs-list content-list">
                {% for _ in range(5) %}
                <div class="subs content">
                    <div class="s-left">
                        <img class="s-cover" src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADU
                    lEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="">
                        <div class="s-bname href"></div>
                    </div>
                    <div class="s-right">
                        {% if session["Uid"] == data["Uid"] %}
                        <div class="s-unsub center-nowrap" data-a="0"></div>
                        {% endif %}
                    </div>

                </div>
                {% endfor %}
                <div class="content foot-wrapper">
                    <div class="prev-arrow arrow">&#9668Prev</div>
                    <div class="index">-/-</div>
                    <div class="next-arrow arrow">Next&#9658</div>
                </div>
            </div>
        </div>
        <!-- for history -->
        <div class="history-list-wrapper list-wrapper">
            <div class="head-wrapper">
                <div class="hide">&#10005</div>
                <div class="list-des"><p class="des-text"></p></div>
            </div>
            <div class="history-list content-list">
                {% for _ in range(8) %}
                <div class="history content">
                    <div class="h-top">
                        <div class="h-title post-title center-nowrap href"></div>
                    </div>
                    <div class="h-bottom">
                        <div class="h-bname board-name center-nowrap href"></div>
                        <div class="h-poster href"></div>
                        <div class="h-time timestamp center-nowrap"></div>
                    </div>
                </div>
                {% endfor %}
                <div class="content foot-wrapper">
                    <div class="prev-arrow arrow">&#9668Prev</div>
                    <div class="index">-/-</div>
                    <div class="next-arrow arrow">Next&#9658</div>
                </div>
            </div>
        </div>



    </div>

    <script>
        $("#avatar-upload").on("click", function () {
            $("#uploadImg").trigger('click');
        });

        function uploadImg(file) {
            if (file.type.substr(0, 5) !== "image") {
                alert("Invalid File Type!");
                return;
            }
            if (file.size > (3 * 1024 * 1024)) {
                alert("Image Too Large!");
                return;
            }
            const formData = new FormData();
            formData.append("file", file);
            $.ajax({
                method: "post",
                url: "/api/upload?action=uploadavatar",
                data: formData,
                processData: false,
                contentType: false,
                success: (data) => {
                    if (data.hasOwnProperty("status")) {
                        alert("Successfully uploaded image!");
                        location.reload();
                    } else {
                        alert(data.error.msg);
                    }
                }
            })
        }

        // view original
        $("#view-origin").on("click", () => {
            window.open($("#avatar-upload").attr("src"), "_blank");
        })

        // view info
        var cur_page = 1;
        var cur_max_page;
        var cur_type;

        $(".status-box").on("click", function () {
            fetchData($(this).index()/2);  // because of the sep line
        })

        $(".hide").on("click", () => {
            hidePopup();
        })

        $(".prev-arrow").on("click", () => {
            cur_page = Math.max(cur_page-1, 1);
            fillData(cur_type);
        })
        $(".next-arrow").on("click", () => {
            cur_page = Math.min(cur_page+1, cur_max_page);
            fillData(cur_type);
        })

        var des_dict = {
            0: "{{ ("My" if data["isCurrent"] else "User") + " Posts"}}",
            3: "Browse History",
            2: "{{ ("My" if data["isCurrent"] else "") + " Subscriptions"}}",
            1: "{{ ("My" if data["isCurrent"] else "User") + " Comments"}}",
        }
        var data_dict = {  // request data only on click on status box
            0: null,  // post data
            3: null,  // history data
            2: null,  // subs data
            1: null, // comment data
        }
        var cls_dict = {
            0: ".post",
            3: ".history",
            2: ".subs",
            1: ".comment",
        }
        var page_size_dict = {
            0: 8,
            1: 8,
            2: 5,
            3: 8,
        }
        function showPopup() {
            $(".pop-up").css("display", "block");
        }

        function showData(type) {  // 0 = post, 1 = history, 2 = subs
            cur_type = type;
            let l_w = $(".list-wrapper");
            l_w.css("display", "none");  // hide all list-wrappers
            l_w.eq(type).css("display", "block");  // show corresponding list-wrapper
            $(".des-text").text(des_dict[type]);  // add description (it doesn't matter for all or only one)
            fillData(type);
        }
        function fillData(type) {
            let cur_page_size = page_size_dict[type];
            cur_max_page = Math.max(Math.ceil(data_dict[type]["count"]/cur_page_size), 1);
            let text = cur_page+"/"+cur_max_page;
            $(".index").eq(type).text(text);  // add page info for corresponding list
            // fill data into list for current page
            let cur_index;
            let info = data_dict[type]["info"];
            for (let i=0;i<cur_page_size;i++) {
                cur_index = (cur_page-1)*cur_page_size + i;  // current index of data_dict
                let has_content = cur_index < info.length;  // whether there is no more content
                let cur_node = $(cls_dict[type]).eq(i);  // current content node in the loop
                let cur_info = (has_content) ? info[cur_index] : {};  // current content object in data_dict
                let get_ = function (name) {  /* only define once */
                    return (has_content) ? cur_info[name] : "";
                }
                // check status, if deleted assign cur_node to .deleted class else remove
                let status = get_("status").toString();
                let deleted = status === "1" || status === "2";
                if (deleted) {
                    cur_node.addClass("deleted");
                } else {
                    cur_node.removeClass("deleted");
                }
                let status_text;
                let status_color;
                if (type === 0 || type === 1) {
                    switch (status) {case "0": status_text="delete"; status_color="blueviolet"; break; case "1":
                        status_text="restore"; status_color="pink"; break; case "2": status_text="banned";
                        status_color="grey";}
                }
                let bname = get_("bname");  // all content object have key "bname"
                let bid = get_("Bid");  // all content object have key "bid"
                if (type === 0) {
                    let p_title = get_("title");
                    let p_time = get_("timestamp");
                    let pid = get_("Pid");
                    $(".p-title", cur_node).text(p_title).attr("data-href", "/post/"+pid)
                        .css("cursor", (deleted)?"default":"pointer");
                    $(".p-bname", cur_node).text(bname).attr("data-href", "/board/"+bid)
                        .css("cursor", (deleted)?"default":"pointer");
                    $(".p-time", cur_node).text(p_time);
                    $(".p-del", cur_node).text(status_text).css("color", status_color)
                        .css("text-decoration", (status_text==="banned")?"none":"underline")
                        .css("cursor", (status_text==="banned")?"default":"pointer")
                        .attr("data-pid", pid);
                } else if (type === 3) {
                    let h_title = get_("title");
                    let is_me = get_("me");
                    let h_poster = is_me ? "me" : get_("nickname");
                    let h_time = get_("LVT");
                    let pid = get_("Pid");
                    let uid = get_("Uid");
                    $(".h-title", cur_node).text(h_title).attr("data-href", "/post/"+pid)
                        .css("cursor", (deleted)?"default":"pointer");
                    $(".h-bname", cur_node).text(bname).attr("data-href", "/board/"+bid)
                        .css("cursor", (deleted)?"default":"pointer");
                    $(".h-poster", cur_node).text(h_poster).css("font-style", (is_me) ? "italic" : "normal")
                        .attr("data-href", "/profile/"+uid);
                    $(".h-time", cur_node).text(h_time);
                } else if (type === 2){
                    let s_cover = (has_content) ? "/cdn/" + get_("cover") : "data:image/gif;base64,iVBORw0KGgo" +
                        "AAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgY" +
                        "GBgAAAABQABh6FO1AAAAABJRU5ErkJggg==";
                    $(".s-cover", cur_node).attr("src", s_cover);
                    $(".s-bname", cur_node).text(bname).attr("data-href", "/board/"+bid);
                    {% if session["Uid"] == data["Uid"] %}
                    $(".s-unsub", cur_node).text((has_content) ? "Unsubsribe" : "").attr("data-bid", bid);
                    {% endif %}
                } else {
                    let c_text = get_("text");
                    let p_title = get_("title");
                    let c_time = get_("timestamp");
                    let pid = get_("Pid");
                    let cid = get_("Cid");
                    $(".c-text", cur_node).text(c_text).attr("data-href", "/post/"+pid)
                        .css("cursor", (deleted)?"default":"pointer");
                    $(".c-ptitle", cur_node).text(p_title).attr("data-href", "/post/"+pid)
                        .css("cursor", (deleted)?"default":"pointer");
                    $(".c-time", cur_node).text(c_time);
                    $(".c-del", cur_node).text(status_text).css("color", status_color)
                        .css("text-decoration", (status_text==="banned")?"none":"underline")
                        .css("cursor", (status_text==="banned")?"default":"pointer")
                        .attr("data-cid", cid);
                }
            }
        }
        // click to jump
        $(".href").on("click", function (){
            location.href = $(this).data("href");
        })

        // send unsub/sub
        $(".s-unsub").on("click", function () {
            let me = $(this);
            let Bid = me.attr("data-bid");
            let action = me.attr("data-a");
            $.ajax({
                method: "POST",
                url: "/api/subscribe",
                dataType: "json",
                data: {Bid: Bid, action: action},
                success: data => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        $(".status-num").eq(2).text(data.subs_count);
                        me.text((action==="0")?"Subscribe":"Unsubscribe").attr("data-a", (action==="0")?"1":"0")
                            .css("color", (action==="0")?"pink":"red");
                        data_dict[2] = null;  // must clear cache, otherwise discrepancy
                    }
                }
            })
        })

        function fetchData(type) {
            // show popup first
            showPopup();
            // if cached, do not fetch new data
            if (data_dict[type]) {return showData(type);}
            // else, go fetch and cache data
            // while data not coming, display loading message (can be simulated by sleeping at server in route "/fetch")
            $(".loading").css("display", "flex");
            $.ajax({
                method: "GET",
                url: "/api/fetch?Uid={{ data["Uid"] }}&type=" + type,
                success: data => {  // when data retrieved, display them
                    $(".loading").css("display", "none");  // hide the loading page
                    if (data.status) {
                        data_dict[type] = data;
                        showData(type);
                    } else {
                        alert("Something went wrong. Try again later.")
                    }
                }
            });
            // clear cache every 10 minutes
            setInterval(() => {
                data_dict[type] = null;
            }, 10*60*1000);
        }
        function hidePopup() {
            cur_page = 1;  // reset page to 1
            $(".pop-up").css("display", "none");  // hide popup
            $(".list-wrapper").css("display", "none");  // hide all list-wrappers
        }

        // delete/restore post
        $(".p-del").on("click", function () {
            let button_text = $(this).text();
            if (!(button_text === "delete" || button_text === "restore")){return}
            let Pid = $(this).data("pid");
            let action = (button_text === "delete") ? 1 : 0;
            $.ajax({
                method: "POST",
                url: "/api/post/" + button_text,
                dataType: "json",
                data: {Pid: Pid},
                success: data => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        $(this).text((action)?"restore":"delete").css("color", (action)?"pink":"blueviolet")
                            .css("text-decoration", "underline").css("cursor", "pointer");
                        let post = $(this).parent().parent(".post");
                        if (action) {
                            post.addClass("deleted");
                        } else {
                            post.removeClass("deleted");
                        }
                    }
                }
            })
        })
        // delete/restore post
        $(".c-del").on("click", function () {
            let button_text = $(this).text();
            if (!(button_text === "delete" || button_text === "restore")){return}
            let Cid = $(this).data("cid");
            let action = (button_text === "delete") ? 1 : 0;
            $.ajax({
                method: "POST",
                url: "/api/comment/" + button_text,
                dataType: "json",
                data: {Cid: Cid},
                success: data => {
                    if (!data.status) {
                        alert(data.error.msg);
                    } else {
                        $(this).text((action)?"restore":"delete").css("color", (action)?"pink":"blueviolet")
                            .css("text-decoration", "underline").css("cursor", "pointer");
                        let cmt = $(this).parent().parent(".comment");
                        if (action) {
                            cmt.addClass("deleted");
                        } else {
                            cmt.removeClass("deleted");
                        }
                    }
                }
            })
        })
    </script>
{% endblock %}
