/*
 * 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 */
/* global OV */

module.exports = (function() {

    'use strict';

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

    // request choice codes

    var requestVoteCastCode = function() {

        var deferred = Q.defer();

        var endpoint = config('endpoints.votecastcodes')
            .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) {

                    var response = JSON.parse(this.responseText);
                    if (response.valid) {

                        try {
                            var voteCastCode = OV.parseCastResponse(response,
                                session('credentials').certificate,
                                session('verificationCardSet').data.voteCastCodeSignerCert,
                                session('certificates')['authenticationTokenSignerCert'],
                                session('ballotBoxCert'),
                                session('votingCardId'),
                                config('electionEventId'),
                                session('verificationCardId'));
                            deferred.resolve(voteCastCode);
                        } catch (e) {
                            deferred.reject(e.message);
                        }

                    } else {
                        if (response.validationError) {
                            deferred.reject(response);
                        } else {
                            deferred.reject('invalid vote cast code');
                        }
                    }

                } else {
                    var response = this.responseText ? JSON.parse(this.responseText) : null;
                    if (response && response.validationError){
                        deferred.reject(response);
                    }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 requestVoteCastCode;

}());
