var TWITCHY = TWITCHY || {};


/**
   - [ ] User Story 1: I can see whether Free Code Camp is currently streaming on Twitch.tv

   - [ ] User Story 2: I can click the status output and be sent directly to the Free Code Camp Twitch.tv channel

   - [ ] User Story 3: If a Twitch user is currently streaming, I can see additional details about what they are streaming

   - [ ] User Story 4: I will see a placeholder navigation if a streamer has closed their Twitch account
                       (or the account never existed).  (Test with brunofin and comster404).
 */



TWITCHY.Main = (function() {
    var streams = [
        "freecodecamp", "esl_sc2", "OgamingSC2", "cretetion",
        "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas",
        "brunofin", "comster404",
    ];

    var streamStatus = {};
    var channelInfo = {};
    var noExistRE = /Channel \'([a-zA-Z0-9_]+)\' does not exist/g;

    var proxy = 'https://cors-anywhere.herokuapp.com/';
    var apiurl = 'https://wind-bow.gomix.me/twitch-api';
    var api = proxy + apiurl;

    var cardtemplate =
        '<div class="col-sm-4"> \
            <div class="card-block">\
              <img class="card-img-top" src="{{STREAMIMAGE}}" width="300" alt="Card image cap">\
              <h3 class="card-title">{{STREAMTITLE}}</h3>\
              <p class="card-text">Status: {{STREAMTEXT}}</p>\
              <a href="#" class="btn btn-primary">Go somewhere</a>\
            </div>\
          </div>\
        </div>';

    var simpletemplate = "<li></li>";

    /**
     */
    function handleChannelInfo(data) {
        var streamDiv = $('#streams'),
	    matches;

        console.log('--- handleChannelInfo ---');
        // console.log(data);

        if (data.hasOwnProperty('error')) {
            // console.log(data);
            console.log(data.message);

	    matches = noExistRE.exec(data.message);
	    if (matches.length == 2) {
		var channelName = matches[1];
		channelInfo[channelName] = {'status': 404, 'message': data.message};
	    }

        } else {
            // console.log('adding', data.name, 'to the channel list');
            channelInfo[data.name] = data;

	    console.log("streams in list:", streams.length, " channels collected:", Object.keys(channelInfo).length);

            var markup = cardtemplate
                .replace("{{STREAMTITLE}}", data.display_name)
                .replace("{{STREAMTEXT}}", data.status)
                .replace("{{STREAMIMAGE}}", data.profile_banner);
            $(markup).appendTo(streamDiv);
        }
    }


    /**
     * Callback for stream info API call.  Stores info about each stream
     * and gets info about each channel.
     */
    function handleStreamInfo(data) {
        var streamname;

        console.log("--- handleStreamInfo ---");
        //console.log(data);

        streamname = data._links.channel.split('/').pop();
        streamStatus[streamname] = data;

        if (data.stream === null) {
            console.log(streamname, 'is offline');
        } else {
            console.log(streamname, 'is currently streaming');
        }

        $.getJSON(api + '/channels/' + streamname, handleChannelInfo).fail(function() {
            console.log("Get channel info for", streamname, "failed");
        });
    }


    /**
     */
    function listStreams() {
        var url;

        for (var i=0; i < streams.length; i++) {
            console.log('---', streams[i], '---');
            url = api + '/streams/' + streams[i];
            $.getJSON(url, handleStreamInfo).fail(function() {
                console.log("--- channelData call failed ----");
            });
        }
    }

    /**
     * Get info about each channel
     */
    function listChannels() {
        var url, i;

        for (i=0; i < streams.length; i++) {
            console.log('---', streams[i], '---');
            url = api + '/channels/' + streams[i];
            $.getJSON(url, handleChannelInfo).fail(function() {
                console.log("--- channelData call failed ----");
            });
        }
    }


    return {
        listStreams: listStreams,
        listChannels: listChannels
    };

})();


// TWITCHY.Main.listStreams();
TWITCHY.Main.listChannels();

@@ -30,25 +30,25 @@
 %0A%0A/**%0A   - %5B
- 
+x
 %5D User Story
@@ -1628,16 +1628,29 @@
  matches
+,%0A%09    status
 ;%0A%0A     
@@ -1952,16 +1952,78 @@
 hes%5B1%5D;%0A
+%09%09console.log('****', channelName, ' does not exist ******');%0A
 %09%09channe
@@ -2334,24 +2334,296 @@
 ).length);%0A%0A
+%09    var streamInfo = streamStatus%5Bdata.name%5D;%0A%09    console.log(%22%3E%3E%3E%3E%3E%3E%3E%3E%3E stream info for%22, data.name, %22is%22, streamInfo);%0A%09    if ((streamInfo === undefined) %7C%7C (streamInfo.stream === null) )%7B%0A%09%09status = %22Currently Offline%22;%0A%09    %7D else %7B%0A%09%09status = data.status;%0A%09    %7D%0A%0A
             
@@ -2754,21 +2754,16 @@
 EXT%7D%7D%22, 
-data.
 status)%0A
@@ -2815,22 +2815,12 @@
 ata.
-profile_banner
+logo
 );%0A 
@@ -3071,32 +3071,35 @@
 amname;%0A%0A       
+ //
  console.log(%22--
@@ -3134,16 +3134,17 @@
       //
+ 
 console.
@@ -4497,19 +4497,16 @@
 %7D)();%0A%0A%0A
-// 
 TWITCHY.
@@ -4525,16 +4525,18 @@
 eams();%0A
+//
 TWITCHY.

Finished user story 1