/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/* global require */

module.exports = (function() {

    'use strict';

    var XMLHttpRequest = XMLHttpRequest || require('xhr2');
    var Q = require('q');
    var config = require('./config.js');
    var session = require('./session.js');

    // lenient json parse

    var jsonparse = function(x) {
        try {
            return JSON.parse(x);
        } catch (ignore) {
            return {};
        }
    };

    // request receipt

    var requestReceipt = function() {

        var deferred = Q.defer();

        var endpoint = config('endpoints.receipts')
            .replace('{tenantId}', config('tenantId'))
            .replace('{electionEventId}', config('electionEventId'))
            .replace('{votingCardId}', session('votingCardId'));

        var xhr = new XMLHttpRequest();
        xhr.open('GET', config('host') + endpoint);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    deferred.resolve(jsonparse(this.responseText));
                } else {
                    deferred.reject(xhr.status);
                }
            }
        };
        xhr.onerror = function() {
            try {
                deferred.reject(xhr.status);
            } catch (e) {
				//This block is intentionally left blank
			}
        };
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.setRequestHeader('authenticationToken', JSON.stringify(session('authenticationToken')));
        xhr.send();

        return deferred.promise;
    };


    return requestReceipt;

}());
