/*
 * Copyright 2015 Canonical Ltd.
 *
 * This file is part of webapps-core.
 *
 * webbrowser-app is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * webbrowser-app is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var api = external.getUnityObject('1.0');
var hub = api.ContentHub;
var activeTransfer;

function _shareRequested(transfer) {
    activeTransfer = transfer;

    transfer.contentType(function(type) {
        if (type === hub.ContentType.Pictures) {
            transfer.items(function(items) {
	        api.launchEmbeddedUI(
                    "HubSharer",
                    uploadPhoto,
                    {"fileToShare": items[0], contentType: type});
            });
        } else if (type === hub.ContentType.Links) {
            transfer.items(function(items) {
	        api.launchEmbeddedUI(
                    "HubSharer",
                    uploadLink,
                    {"fileToShare": items[0], contentType: type});
            });
        }
    });
};
hub.onShareRequested(_shareRequested);

function uploadPhoto(res, onResourceUploadedCallback) {
    var results = JSON.parse(res);
    if (results.status == "cancelled")
        activeTransfer.setState(hub.ContentTransfer.State.Aborted);

    var xhr = new XMLHttpRequest();
    xhr.open( 'POST', 'https://graph.facebook.com/me/photos?access_token=' + results.accessToken, true );
    xhr.onload = xhr.onerror = function() {
        if ( xhr.status == 200 ) {
            window.location.reload();
	    onResourceUploadedCallback(true);
        }
	else {
	    onResourceUploadedCallback(false);
	}
    };

    var contentType = results.fileToShare.split(',')[0].split(':')[1];
    var b64data = results.fileToShare.split(',')[1];

    var byteCharacters = atob(b64data);
    var byteNumbers = new Array(byteCharacters.length);
    for (var i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    var byteArray = new Uint8Array(byteNumbers);

    var div = document.createElement('div');
    div.innerHTML = '<form enctype="multipart/form-data" method="post" id="uploadForm"><textarea id="message" name="message"></textarea></form>';
    document.getElementsByTagName('body')[0].appendChild(div);

    var blob = new Blob([byteArray], {type: contentType});

    var uploadForm = document.forms.namedItem("uploadForm");
    var formData = new FormData(uploadForm);
    formData.append('source', blob);
    formData.append('message', results.message);
    xhr.send(formData);
}

function uploadLink(res, onResourceUploadedCallback) {
    var results = JSON.parse(res);
    if (results.status == "cancelled") {
        activeTransfer.setState(hub.ContentTransfer.State.Aborted);
    }

    var xhr = new XMLHttpRequest();
    xhr.open(
        'POST',
        'https://graph.facebook.com/me/feed?'
            + 'access_token=' + results.accessToken,
        true);
    xhr.onload = xhr.onerror = function() {
        if (xhr.status === 200) {
            window.location.reload();

	    onResourceUploadedCallback(true);
        }
	else {
	    onResourceUploadedCallback(false);
	}
    };

    var div = document.createElement('div');
    div.innerHTML =
        '<form enctype="multipart/form-data" method="post" id="uploadForm"> \
           <textarea id="message" name="message"> \
           </textarea> \
         </form>';
    
    document.getElementsByTagName('body')[0].appendChild(div);

    var uploadForm = document.forms.namedItem("uploadForm");
    var formData = new FormData(uploadForm);
    formData.append('message', results.message);
    formData.append('link', results.fileToShare);
    xhr.send(formData);
}

