/*
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * For more information, please refer to <http://unlicense.org/>
 */


var channel_here = "60dd7f55-9f88-4de6-ad98-b9c4e2810300";
var channel_main_1 = "rc1";
var channel_main_2 = "rc2";

// Not included in Frab XML
slug_map = {
    bitwaescherei: "feb91cb1-eb66-43f1-a86f-f8d43909fbe0",
    c3lounge: "ffa2f0d2-ca0b-41b6-a5cc-78ffc3fe15ff",
    chaoszone: "084fed6f-8da2-4870-b8c2-7a2b1dce88bd",
    csh: "ebc42052-10f7-4aef-bbe9-cfe9026880cc",
    cwtv: "48f5bce3-5b46-44d8-9f36-90bed9bd4be0",
    hacc: "60dd7f55-9f88-4de6-ad98-b9c4e2810300",
    r3s: "c4a577e2-52e7-4f6f-a5c0-e3822d64f84a",
    sendezentrum: "feb91cb1-eb66-43f1-a86f-f8d43909fbe0",
}

var fahrplan = {};
var tweets = {};

/* === EXTERNAL DATA === */
function update_tweets() {
    var request = new XMLHttpRequest();
    request.open('GET', 'https://api.oct.re/tweets-rc3.json', true);
    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            tweets = JSON.parse(this.response);
            update_tweet_ticker();
        } else { console.log(this); }
    };
    request.onerror = function(e) { console.log(e); };
    request.send();
}

function update_fahrplan() {
    var request = new XMLHttpRequest();
    request.open('GET', 'https://api.oct.re/fahrplan.json', true);
    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            fahrplan = JSON.parse(this.response);
            update_fahrplan_html();
        } else { console.log(this); }
    };
    request.onerror = function(e) { console.log(e); };
    request.send();
}

/* === FAHRPLAN === */
var n_here = 3;
var n_main = 3;
var n_other = 8;

function parse_schedule() {
    var fahrplan_parsed = {
        "here": [],
        "main": [],
        "other": [],
    }
    
    for (var i in fahrplan) {
        if (fahrplan_parsed.here.length < n_here
            && (fahrplan[i].roomguid == channel_here || fahrplan[i].room == channel_here)) {
            fahrplan_parsed.here.push({
                title: fahrplan[i].title,
                sub: fahrplan[i].start + " D" + fahrplan[i].day + ", " + fahrplan[i].personnames,
            });
        } else if (fahrplan_parsed.main.length < n_main
                   && (fahrplan[i].roomguid == channel_main_1 || fahrplan[i].room == channel_main_1
                       || fahrplan[i].roomguid == channel_main_2 || fahrplan[i].room == channel_main_2)) {
            fahrplan_parsed.main.push({
                title: fahrplan[i].title,
                sub: fahrplan[i].start + " D" + fahrplan[i].day + " @ "  + fahrplan[i].room + ", " + fahrplan[i].personnames,
            });
        } else if (fahrplan_parsed.other.length < n_other
                   && fahrplan[i].roomguid != channel_here   && fahrplan[i].room != channel_here
                   && fahrplan[i].roomguid != channel_main_1 && fahrplan[i].room != channel_main_1
                   && fahrplan[i].roomguid != channel_main_2 && fahrplan[i].room != channel_main_2) {
            fahrplan_parsed.other.push({
                title: fahrplan[i].title,
                sub: fahrplan[i].start + " D" + fahrplan[i].day + " @ " + fahrplan[i].room,
            });
        }
    }
    
    return fahrplan_parsed;
}

function update_fahrplan_html() {
    fahrplan_parsed = parse_schedule();
    var els = {
        here: document.getElementById("schedule-here"),
        main: document.getElementById("schedule-main"),
        other: document.getElementById("schedule-other"),
    }
    
    els.here.innerHTML = "";
    els.main.innerHTML = "";
    els.other.innerHTML = "";
    
    for (var group in els) {
        for (var i in fahrplan_parsed[group]) {
            var el = document.createElement("div");
            el.className = "item";
            
            var title = document.createElement("div");
            title.className = "title";
            title.innerText = fahrplan_parsed[group][i].title;
            el.appendChild(title);
            
            var sub = document.createElement("div");
            sub.className = "sub";
            sub.innerText = fahrplan_parsed[group][i].sub;
            el.appendChild(sub);
            
            els[group].appendChild(el);
        }
    }
}


/* === TWEETS === */
function update_tweet_ticker() {
    var ticker = document.getElementById("ticker");
    ticker.innerHTML = "";
    for (var i in tweets.data) {
        //console.log(tweets.data[i].text);
        var item = document.createElement("div");
        item.className = "item";
        
        // Look up user
        var user;
        for (var useri in tweets.includes.users) {
            if (tweets.includes.users[useri].id == tweets.data[i].author_id)
                user = tweets.includes.users[useri];
        }
        
        var img = document.createElement("img");
        img.src = user.profile_image_url;
        item.appendChild(img);
        
        var user_el = document.createElement("span");
        user_el.className = "user";
        var uname = user.username;
        user_el.innerText = "@" + uname + ":";
        item.appendChild(user_el);
        
        var content = document.createElement("span");
        content.className = "content";
        var text = tweets.data[i].text;
        text = text.replace(/\n/g, "↲");
        content.innerText = text;
        item.appendChild(content);
        
        ticker.appendChild(item);
    }
}

(function() {
    var query = location.search.substr(1);
    var result = {};
    query.split("&").forEach(function(part) {
        var item = part.split("=");
        result[item[0]] = decodeURIComponent(item[1]);
    });

    if (result.room !== undefined)
        channel_here = result.room;
    
    if (slug_map[channel_here] !== undefined)
        channel_here = slug_map[channel_here];
    
    update_fahrplan();
    update_tweets();
    setInterval(update_fahrplan,60000);
    setInterval(update_tweets, 60000);
})();
