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

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

import de.ivu.wahl.wus.oasis.eml.CandidateList;
import de.ivu.wahl.wus.oasis.eml.EML;
import de.ivu.wahl.wus.oasis.eml.ElectionIdentifierStructure;
import de.ivu.wahl.wus.oasis.eml.kiesraad.ElectionDomain;
import de.ivu.wahl.wus.oasis.eml.kiesraad.ObjectFactory;


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

public class Eml230Wrapper extends AbstractEmlElectionWrapper {

  private ElectionDomain electionDomain;

  public Eml230Wrapper(EML eml) {
    super(eml);

    if (eml.getCandidateList() == null) {
      eml.setCandidateList(of.createCandidateList());
    }

    if (eml.getCandidateList().getElection().isEmpty()) {
      eml.getCandidateList().getElection().add(of.createCandidateListElection());
    }

    CandidateList.Election election = eml.getCandidateList().getElection().get(0);

    if (election.getElectionIdentifier() == null) {
      election.setElectionIdentifier(of.createElectionIdentifierStructure());
    }

  }

  private static ElectionDomain findeElectionDomain(ElectionIdentifierStructure electionIdentifier) {
    for (Object o : electionIdentifier.getAny()) {
      if (o instanceof ElectionDomain) {
        return (ElectionDomain) o;
      }
    }

    ElectionDomain result = new ObjectFactory().createElectionDomain();
    electionIdentifier.getAny().add(result);
    return result;
  }

  public ElectionDomain getOrCreateElectionDomain() {
    if (electionDomain == null) {
      electionDomain = findeElectionDomain(getElection().getElectionIdentifier());

    }
    return electionDomain;
  }

  public String getElectionId() {
    return getElectionIdentifierStructure().getId();
  }

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

  private CandidateList.Election getElection() {
    return getContent().getCandidateList().getElection().get(0);
  }

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

  public Eml230ContestWrapper addContest() {
    Eml230ContestWrapper result = new Eml230ContestWrapper();
    getElection().getContest().add(result.getContent());
    return result;
  }

}
