package de.ivu.elect.exchange.wahl;

import de.ivu.elect.business.datei.entity.FileType;
import de.ivu.elect.business.exchange.control.FileFormat;
import de.ivu.elect.business.exchange.control.FileKonfiguration;
import de.ivu.elect.business.exchange.control.MappingException;
import de.ivu.elect.business.wahl.boundary.WahlKonfigurationImporter;
import de.ivu.elect.business.wahl.entity.WahlKonfiguration;
import de.ivu.elect.business.wahl.entity.WahlKonfigurationExchangeContext;
import de.ivu.elect.exchange.XmlImportMapper;
import de.ivu.elect.jee.exchange.Violations;
import de.ivu.elect.jee.exchange.XmlMarshaller;
import de.ivu.elect.jee.exchange.XmlSchemaLoader;

import javax.inject.Inject;
import javax.xml.bind.JAXBException;
import java.io.InputStream;

/**
 *  on 01.07.2015.
 */
public class DefaultXMLWahlKonfigurationImportMapper implements WahlKonfigurationImportMapper, XmlImportMapper {

  public static final String FILE_FORMAT = WahlKonfigurationImporter.FILE_FORMAT_DEFAULT;

  private static final String SCHEMA_RESOURCE_NAME = "elect-interfaces-konfiguration.xsd";

  @Inject
  protected transient XmlMarshaller<de.ivu.elect.interfaces.core.konfiguration.WahlKonfiguration> xmlMarshaller;

  @Inject
  protected transient XmlSchemaLoader schemaLoader;

  @Inject
  private transient WahlKonfigurationMapper wahlkonfigurationMapper;

  @Override
  public WahlKonfiguration deserialize(InputStream is, WahlKonfigurationExchangeContext noContext, FileKonfiguration fileKonfiguration) throws MappingException {
    try {
      return wahlkonfigurationMapper.mappe(xmlMarshaller.deserialize(de.ivu.elect.interfaces.core.konfiguration.WahlKonfiguration.class, is));
    } catch (JAXBException e) {
      throw new MappingException(e.getMessage(), e);
    }
  }

  @Override
  public Violations validateInputFormat(InputStream is, WahlKonfigurationExchangeContext noContext, FileKonfiguration fileKonfiguration) {
    return validateXml(is, xmlMarshaller, schemaLoader, SCHEMA_RESOURCE_NAME, de.ivu.elect.interfaces.core.konfiguration.WahlKonfiguration.class);
  }

  @Override
  public FileFormat getFileFormat() {
    return new FileFormat(FILE_FORMAT, FileType.XML);
  }

  @Override
  public boolean isAcceptContext(WahlKonfigurationExchangeContext noContext) {
    return true;
  }
}
