
package de.ivu.elect.exchange.rolle.xml;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.xml.bind.JAXBException;

import de.ivu.elect.business.benutzerverwaltung.entity.Rolle;
import de.ivu.elect.business.benutzerverwaltung.entity.RolleExchangeContext;
import de.ivu.elect.business.datei.entity.FileType;
import de.ivu.elect.business.exchange.control.FileKonfiguration;
import de.ivu.elect.business.exchange.control.MappingException;
import de.ivu.elect.exchange.rolle.AbstractDefaultRolleMapper;
import de.ivu.elect.jee.exchange.Violations;
import de.ivu.elect.jee.exchange.XmlMarshaller;

public class DefaultXmlRolleMapper extends AbstractDefaultRolleMapper<DefaultExchangeRolleXmlDTO> {

  @Inject
  protected transient XmlMarshaller<DefaultExchangeXmlRolleListe> xmlMarshaller;

  public DefaultXmlRolleMapper() {
    super();
  }

  @Override
  public void serialize(List<Rolle> object, OutputStream os, RolleExchangeContext context, FileKonfiguration fileKonfiguration) throws MappingException {
    try {
      xmlMarshaller.serialize(mappeEntityInternToExtern(object), os);
    } catch (JAXBException e) {
      throw new MappingException(e.getMessage(), e);
    }
  }

  @Override
  public List<Rolle> deserialize(InputStream is, RolleExchangeContext context, FileKonfiguration fileKonfiguration) throws MappingException {
    try {
      return mappeEntityExternToIntern(xmlMarshaller.deserialize(DefaultExchangeXmlRolleListe.class, is));
    } catch (JAXBException e) {
      throw new MappingException(e.getMessage(), e);
    }
  }

  @Override
  public Violations validateInputFormat(InputStream is, RolleExchangeContext context, FileKonfiguration fileKonfiguration) {
    return new Violations();
  }

  @Override
  public FileType getFileType() {
    return FileType.XML;
  }

  @Override
  protected DefaultExchangeRolleXmlDTO createEntity() {
    return new DefaultExchangeRolleXmlDTO();
  }

  protected DefaultExchangeXmlRolleListe mappeEntityInternToExtern(List<Rolle> entityListe) {
    DefaultExchangeXmlRolleListe result = new DefaultExchangeXmlRolleListe();
    for (Rolle entity : entityListe) {
      result.getRollen().add(mappeEntity(entity));
    }
    return result;
  }

  protected List<Rolle> mappeEntityExternToIntern(DefaultExchangeXmlRolleListe entityListe) {
    List<Rolle> mappedBenutzer = new ArrayList<>(entityListe.getRollen().size());

    for (DefaultExchangeRolleXmlDTO entity : entityListe.getRollen()) {
      mappedBenutzer.add(mappeEntity(entity));
    }

    return mappedBenutzer;
  }

  @Override
  public boolean isAcceptContext(RolleExchangeContext context) {
    return true;
  }
}
