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

const _ = require('lodash');


function calculateMaximumPossibleWriteins (ballot) {

  return _.reduce(ballot.contests, (total, contest) => {

    total += _.reduce(contest.questions, (accum, question) => {

      if (question.writeIn === 'true') {

        accum += parseInt(question.max);

      }

      return accum;

    }, 0);

    return total;

  }, 0);

}

function getContestValidWriteInsRepresentations (contest) {

  const writeInsAttrs = _.reduce(contest.questions, (WIAttrs, question) => {

    if (question.writeInAttribute) {

      WIAttrs.push(question.writeInAttribute);

    }

    return WIAttrs;

  }, []);

  return _.reduce(contest.options, (validWriteInsRepresentations, option) => {

    if (_.includes(writeInsAttrs, option.attribute)) {

      validWriteInsRepresentations.push(option.representation);

    }

    return validWriteInsRepresentations;

  }, []);

}

function getBallotWriteInsRepresentations (ballot) {

  return _.reduce(ballot.contests, (result, contest) => {

    result = result.concat(getContestValidWriteInsRepresentations(contest));

    return result;

  }, []);

}

module.exports = (() => {

  return {
    calculateMaximumPossibleWriteins: calculateMaximumPossibleWriteins,
    getBallotWriteInsRepresentations: getBallotWriteInsRepresentations,
  };

})();
