/*
 * 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
 */
(function() {

    'use strict';

    angular.module('ballotprinter', [])

    .factory('ballotprinter', function(_) {

        var print = function(ballots) {

            _.each(ballots, function(ballot) {
                print_ballot(ballot);
            });

        };

        var b64decodeUnicode = function(b64) {
            return decodeURIComponent(Array.prototype.map.call(atob(b64), function(c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
            }).join(''));
        };


        var print_ballot = function(ballot) {

            _.each(ballot.contests, function(contest) {
                _.each(contest.options, function(option) {

                    // let's pretend this is some b64encoded JSON we need to expand:

                    try {

                        var expanded = JSON.parse(b64decodeUnicode(option.defaultText));

                        // if this didn't crash, just substitute the expanded text:

                        option.defaultText = expanded;

                    } catch (ignore) {
                        // nope!
                    }

                });
            });

        };

        // export

        return {
            print: print
        };

    });

})();
