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

import java.util.Date;

import javax.annotation.Nullable;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import de.ivu.elect.nl.eml.XmlHelper;
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.ElectionSubcategoryType;
import de.ivu.wahl.wus.oasis.eml.kiesraad.ObjectFactory;

public abstract class AbstractEmlElectionWrapper extends AbstractWrapper<EML> {

  protected AbstractEmlElectionWrapper(EML content) {
    super(content);

    if (getContent().getManagingAuthority() == null) {
      getContent().setManagingAuthority(of.createManagingAuthorityStructure());
    }
    if (getContent().getManagingAuthority().getAuthorityAddress() == null) {
      getContent().getManagingAuthority().setAuthorityAddress(of.createAuthorityAddressStructure());
    }
  }

  public ManagingAuthorityWrapper getManagingAuthority() {
    return new ManagingAuthorityWrapper(getContent().getManagingAuthority());
  }

  public abstract ElectionIdentifierStructure getElectionIdentifierStructure();

  @Nullable
  public String getElectionDate() {
    for (Object o : getElectionIdentifierStructure().getAny()) {
      if (o instanceof Element) {
        Element e = (Element) o;
        if (StringUtils.isNotBlank(e.getTagName()) && e.getTagName().contains("ElectionDate")) {
          Node firstChild = e.getFirstChild();
          if (firstChild != null) {
            String nodeValue = firstChild.getNodeValue();
            if (StringUtils.isNotBlank(nodeValue)) {
              return nodeValue;
            }
          }
        }
      }
    }

    return null;
  }

  public void addElectionDate(Date electionDate) {
    if (electionDate!=null) {
      getElectionIdentifierStructure().getAny().add(new ObjectFactory().createElectionDate(XmlHelper.mappeDateTimeToCalendarDate(electionDate)));
    }
  }

  public void addNominationDate(Date nominationDate) {
    if (nominationDate != null) {
      getElectionIdentifierStructure().getAny().add(new ObjectFactory().createNominationDate(XmlHelper.mappeDateTimeToCalendarDate(nominationDate)));
    }
  }

  public void addElectionSubcategory(ElectionSubcategoryType electionSubcategory) {
    getElectionIdentifierStructure().getAny().add(new ObjectFactory().createElectionSubcategory(electionSubcategory));
  }

  public void addElectionDomain(String id, String domain) {

    ElectionDomain electionDomain  = new ObjectFactory().createElectionDomain();
    electionDomain.setId(id);
    electionDomain.setValue(domain);

    getElectionIdentifierStructure().getAny()
        .add(new JAXBElement<>(new QName("http://www.kiesraad.nl/extensions", "ElectionDomain"), ElectionDomain.class, null, electionDomain));

  }

}
