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

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

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

import de.ivu.elect.jee.exchange.JAXBUtil;
import de.ivu.elect.nl.eml.XmlHelper;
import de.ivu.wahl.wus.oasis.eml.ManagingAuthorityStructure;
import de.ivu.wahl.wus.oasis.eml.kiesraad.CreatedByAuthority;
import de.ivu.wahl.wus.oasis.eml.kiesraad.ObjectFactory;

public class ManagingAuthorityWrapper extends AbstractWrapper<ManagingAuthorityStructure> {
  protected ManagingAuthorityWrapper(ManagingAuthorityStructure content) {
    super(content);

    if (content.getAuthorityIdentifier() == null) {
      content.setAuthorityIdentifier(of.createAuthorityIdentifierStructure());
    }

  }

  public String getAuthorityId() {
    return getContent().getAuthorityIdentifier().getId();
  }

  public void setAuthorityId(String authorityId) {
    getContent().getAuthorityIdentifier().setId(authorityId);
  }

  public String getAuthorityName() {
    return getContent().getAuthorityIdentifier().getValue();
  }

  public void setAuthorityName(String authorityName) {
    getContent().getAuthorityIdentifier().setValue(authorityName);
  }

  protected CreatedByAuthority getCreatedByAuthorityReadOnly() {
    for (Object o : getContent().getAny()) {
      if (o instanceof CreatedByAuthority) {
        return (CreatedByAuthority) o;
      }
      if (o instanceof Element) {
        Element e = (Element) o;
        if (StringUtils.isNotBlank(e.getTagName()) && e.getTagName().contains("CreatedByAuthority")) {
          String xmlString = XmlHelper.elementToString(e);
          try {
            return new JAXBUtil().unmarshal(CreatedByAuthority.class, new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)));
          } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
          }
        }
      }
    }
    return new ObjectFactory().createCreatedByAuthority();

  }

  public String getCreatedByAuthorityId() {
    return getCreatedByAuthorityReadOnly().getId();
  }

  protected void setCreatedByAuthority(CreatedByAuthority createdByAuthority) {
    getContent().getAny().clear();
    getContent().getAny().add(createdByAuthority);
  }

  public void setCreatedByAuthorityId(String createdByAuthorityId) {
    CreatedByAuthority createdByAuthorityReadOnly = getCreatedByAuthorityReadOnly();
    createdByAuthorityReadOnly.setId(createdByAuthorityId);
    setCreatedByAuthority(createdByAuthorityReadOnly);
  }

  public String getCreatedByAuthorityName() {
    return getCreatedByAuthorityReadOnly().getContent();
  }

  public void setCreatedByAuthorityName(String createdByAuthorityName) {
    CreatedByAuthority createdByAuthorityReadOnly = getCreatedByAuthorityReadOnly();
    createdByAuthorityReadOnly.setContent(createdByAuthorityName);
    setCreatedByAuthority(createdByAuthorityReadOnly);
  }

}
