/*
 * 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 */
/* jshint maxlen: 666  */

var _                   = require('lodash');
var getText             = require('./util.js').getText;
var parseCorrectnessIds = require('./id-correctness.js');

var parsers   = {
    listsAndCandidates : require('./lists-and-candidates.js'),
    options           : require('./options.js')
};

var getParser = function(contestType) {
    var parser = parsers[contestType];
    if (parser) {
        return parser;
    } else {
      console.error('Undefined contest type: ' + contestType);
      throw new Error('Undefined contest type: ' + contestType);
    }
}

module.exports = (function() {

    'use strict';

    var i18nTexts = null;
	
	var parseContest = function(contestJson) {
        var parser = getParser(contestJson.template);
        return parser.parse(contestJson);
    };
	
    var parseBallot = function(ballotJson) {

        var ballot = new OV.Ballot(ballotJson.id);

        _.each(ballotJson.contests, function(c) {
            ballot.addContest(parseContest(c));
        });

        var correctnessIds = {};
        _.each(ballotJson.contests, function(contest) {
            _.each(contest.options, function(option) {
                if (option.representation) {
                    parseCorrectnessIds(correctnessIds, option, contest.attributes);
                }
            });
        });

        ballot.correctnessIds = correctnessIds;
        ballot.writeInAlphabet = ballotJson.writeInAlphabet;

        return ballot;

    };

	var setLocale = function(ballot, locale) {
        var txt = getLocaleText(locale);

        _.each(ballot.contests, function(contest) {
            ballot.title = getText(txt, ballot.id, 'title', null, 'ballot');
            ballot.description = getText(txt, ballot.id, 'description', null, 'ballot');

            var parser = getParser(contest.template);
            parser.setLocale(contest, txt);
        });
    };
	
    var parseTexts = function(ballot, ballotTextsJson) {

        i18nTexts = ballotTextsJson;
        if (ballotTextsJson[0].locale) {
            setLocale(ballot, ballotTextsJson[0].locale);
        } else {
            console.log('Ballot i18n not found');
        }
    };


    var getLocaleText = function(locale) {

        var i18n = _.find(i18nTexts, {
            locale: locale
        });
        if (!i18n) {
            i18n = _.find(i18nTexts, {
                locale: locale.replace('-', '_')
            });
        }
        var txt = i18n ? i18n.texts : {};

        return txt;
    };

    return {
        parseBallot: parseBallot,
        parseTexts: parseTexts,
        setLocale: setLocale
    };

}());
