<!DOCTYPE html>
<html>
<!--
    This page lets you see new posts as they are made in a subreddit.
    Just type a subreddit's name into the box, and press Start.

    Although the default behavior is to interpret the box's contents as a subreddit
    name, you can actually insert something like "/u/goldensights/m/loband" to watch
    https://reddit.com/u/goldensights/m/loband/new
-->
<head>
    <title>/new</title>
    <meta charset="UTF-8">
</head>

<body>
    <div id="control_panel">
        <input type="text" id="subreddit_field" placeholder="/r/learnpython" autofocus>
        <button id="start_button" onclick="start()">Start</button>
        <a id="browser_link"></a>
        <button id="clear_button" onclick="clear_workspace()">Clear workspace</button>
    </div>

    <div id="workspace">
    </div>
</body>

</html>


<style>
html
{
    background-color: #1b1c18;
}
body
{
    background-color: #272822;
    margin-left:  10%;
    margin-right: 10%;
    padding: 5px;
}


#control_panel
{
    background-color: #284142;
    padding: 5px;
}


.submission .text
{
    color: #aaa;
    margin-left: 16px;
}

a
{
    color: #ddd;
    text-decoration: none;
    font-family: sans-serif;
}

a:hover
{
    text-decoration: underline;
}

.delete_button
{
    position: absolute;
    top: 0px;
    right: 0px;
    height: 100%;
    width: 5%;

    border: 0px;
    background-color: #b53030;
}

.submission
{
    position: relative;

    padding: 10px;
    padding-top: 20px;
    padding-bottom: 20px;
    padding-right: 6%; /*for the delete button*/

    margin: 10px;
    margin-top: 20px;
    margin-bottom: 20px;

    box-shadow: 5px 5px 10px 0px rgba(0,0,0,0.5);
    background-color: #284142;
}
</style>


<script type="text/javascript">
/*
    Thanks Joe Marini for the tab focus code
    http://www.html5rocks.com/en/tutorials/pagevisibility/intro/
*/

var CHECK_DELAY = 30 * 1000;
var CONTROL_PANEL = document.getElementById("control_panel");
CONTROL_PANEL.default_color = CONTROL_PANEL.style.backgroundColor;
var WORKSPACE = document.getElementById("workspace");

var id_cache = [];
var id_cache_size = 20;

var first_loop = true;
var unread_notification_count = 0;
var subreddit = "";
var check_timer = null;

var page_focused_cached;


var HTTPClient = function()
{
    /* Thanks ttgagne http://stackoverflow.com/a/22076667 */
    var asynchronous = true;
    this.get = function(url, callback)
    {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function()
        {
            // console.log(request.readyState);
            // console.log(request.status);
            if (request.readyState == 4)
            {
                if (request.status == 200)
                {
                    CONTROL_PANEL.style.backgroundColor = CONTROL_PANEL.default_color;
                    callback(request.responseText);
                }
                else
                {
                    CONTROL_PANEL.style.backgroundColor = "#f00";
                }
            }
        }
        request.open("GET", url, asynchronous);
        //request.withCredentials = true;
        request.send(null);
    }
}

function create_submission_div(submission)
{
    var div = document.createElement("div");
    div.className = "submission";

    var anchor = document.createElement("a");
    anchor.innerHTML = "/r/" + submission["subreddit"] + " - " + submission["title"];
    anchor.href = "https://reddit.com/r/" + submission["subreddit"] + "/comments/" + submission["id"];
    anchor.target = "_blank";

    var text = document.createElement("div");
    text.className = "text";
    var template = document.createElement("template");
    var txt = document.createElement("textarea");
    txt.innerHTML = unescape(submission["selftext_html"]);
    template.innerHTML = txt.value;
    text.appendChild(template.content);

    var delete_button = document.createElement("button");
    delete_button.className = "delete_button";
    delete_button.div = div;
    delete_button.innerHTML = "X";
    delete_button.onclick = function()
    {
        this.div.parentElement.removeChild(this.div);
    }

    // var timestamp = document.createElement("span");
    // var submission_time = new Date(submission["created_utc"])
    // timestamp.innerHTML = "" + submission_time.getHours() + ":" + submission_time.getMinutes();

    div.appendChild(anchor);
    div.appendChild(text);
    div.appendChild(delete_button);
    return div;
}

function apply_to_page(response_json)
{
    var j = JSON.parse(response_json);
    var submissions = j["data"]["children"];
    submissions.reverse();  // newest last
    var new_items = 0;
    for (var index = 0; index < submissions.length; index += 1)
    {
        var submission = submissions[index]["data"];
        if (id_cache.includes(submission["id"]))
        {
            continue;
        }

        id_cache.push(submission["id"]);

        if (first_loop)
        {
            continue;
        }

        new_items += 1;

        div = create_submission_div(submission);
        WORKSPACE.insertBefore(div, WORKSPACE.firstChild);
        // WORKSPACE.appendChild(div);
    }
    console.log("+" + new_items);
    if (new_items > 0 && !page_focused_cached)
    {
        unread_notification_count += new_items;
        update_title();
    }

    while (id_cache.length < id_cache_size)
    {
        id_cache.shift();
    }

    first_loop = false;
}

function check_forever()
{
    clearTimeout(check_timer);
    check_once();
    check_timer = setTimeout(check_forever, CHECK_DELAY);
}

function check_once()
{
    console.log("checking");
    if (subreddit == "")
    {
        console.log("no subreddit");
        return;
    }
    var url = "https://api.reddit.com" + subreddit + "/new.json";
    session.get(url, apply_to_page);
}

function clear_workspace()
{
    while (WORKSPACE.children.length > 0)
    {
        WORKSPACE.removeChild(WORKSPACE.firstChild);
    }
}

function on_focus_change()
{
    if (page_focused_fresh())
    {
        unread_notification_count = 0;
        update_title();
    }
}

function page_focused_fresh()
{
    var property = visibility_property();
    if (!property)
    {
        page_focused_cached = true;
        return true;
    }
    else
    {
        page_focused_cached = !document[property];
    }
    return page_focused_cached;
}

function sort_submission_comparator(submission_1, submission_2)
{
    created_1 = submission_1["created_utc"];
    created_2 = submission_2["created_utc"];

    if (created_1 < created_2)
        {return -1;}
    if (created_1 > created_2)
        {return 1;}
    return 0;
}

function start()
{
    console.log("start");
    first_loop = true;
    clear_workspace();
    var field = document.getElementById("subreddit_field");
    var text = field.value;
    text = text.replace("/u/", "/user/");
    if (text.indexOf("/") == -1)
    {
        text = "/r/" + text;
    }
    subreddit = text;
    var link = document.getElementById("browser_link");
    var url = "https://reddit.com" + subreddit + "/new";
    link.href = url;
    link.innerHTML = url;
    update_title();
    check_forever();
}

function update_title()
{
    var title = subreddit + "/new";
    if (unread_notification_count > 0)
    {
        title = "(" + unread_notification_count + ") " + title;
    }
    document.title = title;
}

function visibility_property()
{
    var prefixes = ["webkit","moz","ms","o"];
    
    if ("hidden" in document)
    {
        return "hidden";
    }

    for (var i = 0; i < prefixes.length; i++)
    {
        hidden_attribute = prefixes[i] + "Hidden";
        if ((hidden_attribute) in document) 
            return hidden_attribute;
    }

    return null;
}


page_focused_fresh();

var my_visibility_property = visibility_property();
if (my_visibility_property)
{
      var my_event_name = my_visibility_property.replace(/[H|h]idden/,'') + 'visibilitychange';
      document.addEventListener(my_event_name, on_focus_change);
}

var session = new HTTPClient();
</script>