package de.ivu.elect.nl.eml.readable;

import java.util.Collections;
import java.util.List;

import de.ivu.wahl.wus.oasis.eml.Count;
import de.ivu.wahl.wus.oasis.eml.EML;
import de.ivu.wahl.wus.oasis.eml.ElectionIdentifierStructure;


import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;

public class Eml510Wrapper extends AbstractEmlElectionWrapper {

  public Eml510Wrapper(EML content) {
    super(content);

    if (getContent().getCount()==null){
      getContent().setCount(of.createCount());
    }

    // Unsinnig, aber soll so: ELECTVAPP-491
    if (getContent().getCount().getEventIdentifier()==null){
      getContent().getCount().setEventIdentifier(of.createEventIdentifierStructure());
    }

    if (getContent().getCount().getElection().isEmpty()) {
      getContent().getCount().getElection().add(of.createCountElection());
    }

    if (getContent().getCount().getElection().get(0).getElectionIdentifier()==null) {
      getContent().getCount().getElection().get(0).setElectionIdentifier(of.createElectionIdentifierStructure());
    }

    if (getContent().getCount().getElection().get(0).getContests() == null) {
      getContent().getCount().getElection().get(0).setContests(of.createCountElectionContests());
    }

  }

  public List<Eml510ContestWrapper> getContest() {
    return getElection().getContests().getContest().stream().map(Eml510ContestWrapper::new).collect(collectingAndThen(toList(), Collections::unmodifiableList));
  }

  public Eml510ContestWrapper addContest() {
    Count.Election.Contests.Contest countElectionContestsContest = of.createCountElectionContestsContest();
    getElection().getContests().getContest().add(countElectionContestsContest);
    return new Eml510ContestWrapper(countElectionContestsContest);
  }

  @Override
  public ElectionIdentifierStructure getElectionIdentifierStructure() {
    return getElection().getElectionIdentifier();
  }

  private Count.Election getElection() {
    return getContent().getCount().getElection().get(0);
  }

}
