/* Copyright (c) 2013 Isaac Dontje Lindell
 * This is free software. See LICENSE for more information */


/* oauth boilerplate */
var clientId = '935106300740-kug08d5pcg9rl6u68trr5qeo4fonf1m4.apps.googleusercontent.com';
var apiKey = 'AIzaSyAgnIILA5vo46DFldSndtc6luC3Nwlj8Is';

// TODO we should only need readonly access
var scopes = ['https://www.googleapis.com/auth/calendar',
              'https://www.googleapis.com/auth/calendar.readonly'];

function handleClientLoad() {
    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuth, 1);
}

function checkAuth() {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

function handleAuthResult (authResult) {
    var authorizeButton = document.getElementById('authorize-button');
    if (authResult && !authResult.error) {
        authorizeButton.style.visibility = 'hidden';
        makeApiCall();
    } else {
        authorizeButton.style.visibility = '';
        authorizeButton.onclick = handleAuthClick;
    }
}

function handleAuthClick(event) {
    // get authorization to use private data
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
    return false;
}
/* end Oauth boilerplate */


// load the API and exercise it
function makeApiCall () {
    // load the GCalendar API
    gapi.client.load('calendar', 'v3', function () {
        // Assemble the API request to list all calendars
        var request = gapi.client.calendar.calendarList.list();
        
        // make the API request
        request.execute(displayCalendarList);
    });
}

// handle the calendar list
function displayCalendarList (resp) {
    var container = $('<div></div>');
    container.addClass('calendar-list-container');

    $.each(resp.items, function (index, item) {
        var el = $("<li></li>");

        var button = $('<button></button>');
        button.text(item.summary);
        button.attr('data-calendar-id', item.id);
        button.attr('onclick', 'handleCalendarSelection("' + item.id + '");');

        el.append(button);
        container.append(el);
    });

    $('body').append(container);
}


function handleCalendarSelection (calendarId) {
    console.log('Selected calendar id: ' + calendarId); // TODO remove

    // remove the calendar list
    $('.calendar-list-container').remove();

    // get all events on the selected calendar
    gapi.client.load('calendar', 'v3', function () {
        var request = gapi.client.calendar.events.list({
            'calendarId': calendarId,
            'singleEvents': true,
            'orderBy': 'startTime'
        });

        request.execute(sumEventTimes);
    });
}

function sumEventTimes (eventsResp) {
    console.log(eventsResp);  // TODO remove eventually

    var events = eventsResp.items;

    var totals = {};
    $.each(events, function(index, event) {
        var eventName = event.summary;

        var start = moment(event.start.dateTime);
        var end = moment(event.end.dateTime);
        var duration = moment.duration(end.diff(start, 'minutes'), 'minutes');

        if (!totals[eventName]) {
            totals[eventName] = moment.duration(0);
        }
        totals[eventName].add(duration);

    });

}

function displayEventTimeTotals (totals) {
    var container = $('<div></div>');
    container.addClass('calendar-event-list-container');

    console.log('totals:'); // TODO remove
    console.log(totals);

    $.each(totals, function (key, item) {
        var el = $('<li></li>');

        var text = key + ': ' + item.asHours() + ' hours';
        el.text(text);

        container.append(el);
    });

    $('body').append(container);
}
@@ -2356,24 +2356,1191 @@
 .remove();%0A%0A
+    // ask for the date range%0A    var start = $('%3Cinput /%3E');%0A    start.attr('type', 'text');%0A    start.addClass('datepicker start-date');%0A    start.attr('placeholder', 'Start date');%0A%0A    var end = $('%3Cinput /%3E');%0A    end.attr('type', 'text');%0A    end.addClass('datepicker end-date');%0A    end.attr('placeholder', 'End date');%0A%0A    var submitButton = $('%3Cbutton%3E%3C/button%3E');%0A    submitButton.attr('type', 'button');%0A    submitButton.attr('onclick', 'getEvents(%22' + calendarId + '%22);');%0A    submitButton.addClass('submit-button');%0A    submitButton.text('Sum Event Times');%0A%0A    var body = $('body');%0A    body.append(start);%0A    body.append(end);%0A    body.append(submitButton);%0A%0A    // activate datepicker%0A    $('.datepicker.start-date').datepicker(%7Bformat: %22mm/dd/yyyy%22%7D);%0A    $('.datepicker.end-date').datepicker(%7Bformat: %22mm/dd/yyyy%22%7D);%0A%7D%0A%0Afunction getEvents(calendarId) %7B%0A    var start = moment($('.start-date').val());%0A    var end = moment($('.end-date').val());%0A%0A    // set end datetime to midnight%0A    end.hour('24');%0A%0A    // remove the start, end, and submit button%0A    $('.start-date').remove();%0A    $('.end-date').remove();%0A    $('.submit-button').remove();%0A%0A
     // get a
@@ -3790,16 +3790,92 @@
 artTime'
+,%0A            'timeMin': start.toDate(),%0A            'timeMax': end.toDate()
 %0A       
@@ -3924,24 +3924,25 @@
 s);%0A    %7D);%0A
+%0A
 %7D%0A%0Afunction 
@@ -4477,25 +4477,24 @@
 (duration);%0A
-%0A
     %7D);%0A%0A%7D%0A%0A
@@ -4482,32 +4482,68 @@
 tion);%0A    %7D);%0A%0A
+    displayEventTimeTotals(totals);%0A
 %7D%0A%0Afunction disp

allow selection of start and end range