/*
 * Copyright (c) eHealth
 */

package be.fgov.ehealth.technicalconnector.tests.beid.tlv;

import java.io.IOException;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import be.ehealth.technicalconnector.utils.MarshallerHelper;
import be.fedict.commons.eid.client.FileType;
import be.fgov.ehealth.technicalconnector.tests.beid.domain.eidviewer.Card;
import be.fgov.ehealth.technicalconnector.tests.beid.domain.eidviewer.File;

/**
 * Created by EH053 on 13/04/2016.
 */
public class XmlTestCardTLVFileGenerator implements TLVFileGenerator {

    private static final Logger LOG = LoggerFactory.getLogger(XmlTestCardTLVFileGenerator.class);

    private static MarshallerHelper<Card, Card> helper = new MarshallerHelper<Card, Card>(Card.class, Card.class);

    @Override
    public byte[] generate(FileType fileType, String location) {
        try {
            Card card = helper.toObject(ConnectorIOUtils.getResourceAsStream(location));
            String id = new String(Hex.encodeHex(fileType.getFileId()));
            LOG.debug("Processing id: " + id);
            for (File file : card.getFile()) {
                if (file.getId()
                        .equalsIgnoreCase(id)) {
                    try {
                        return Hex.decodeHex(file.getContent()
                                                 .toCharArray());
                    } catch (DecoderException e) {
                        throw new IOException(e);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Unable to generate content", e);
        }
        return null;
    }
}
