/**
 *  Background communication
 */

function sendMessage ( message , callback )
{
    chrome.runtime.sendMessage ( { data: message } , callback );
}

function sendCommand ( cmd , params , callback )
{
    sendMessage ( { cmd: cmd , params: params } , callback );
}

var params = {};
var search = document.location.search;
if ( search.indexOf ( '?' ) == 0 )
{
    search = search.substr ( 1 );
}
var pares = search.split ( /&/ );
pares.forEach ( element => {
    if ( element.indexOf ( '=' ) != -1 )
    {
        params [ element.substring ( 0 , element.indexOf ( '=' ) ) ] = element.substring ( element.indexOf ( '=' ) + 1 );
    }
} );

function fileReceived ( data )
{
    if ( data.errnum == 0 )
    {
        jQuery ( document.body ).append ( '<a href="' + window.URL.createObjectURL ( b64toBlob ( data.data.value.data , data.data.value.type ) ) + '" id="enlace"' + ( data.data.value.type.indexOf ( 'image/' ) != 0 ? 'download="' + data.data.value.name + '"' : '' ) + '></a>' );

        jQuery ( 'a#enlace' )[0].click();
    }
}
jQuery ( document ).ready ( function()
{
    if ( typeof params.permission != 'undefined' )
    {
        sendCommand ( 'getFile' , { permission: params.permission , field: params.field } , fileReceived );
    }
    else if ( typeof params.claim != 'undefined' )
    {
        sendCommand ( 'getFile' , { claimType: params.claimType , claim: params.claim , field: params.field } , fileReceived );
    }
} );
 