package com.atlassian.stash.internal.backup.liquibase;

import com.atlassian.stash.internal.backup.liquibase.xml.DefaultXmlEncoder;
import com.atlassian.stash.internal.backup.liquibase.xml.PrettyXmlWriter;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.OutputStream;

import static com.atlassian.stash.internal.backup.liquibase.LiquibaseConstants.ENCODING;
import static com.google.common.base.Preconditions.checkNotNull;

@Component
public class DefaultLiquibaseXmlWriterFactory implements LiquibaseXmlWriterFactory {

    @Override @Nonnull
    public LiquibaseXmlWriter create(@Nonnull OutputStream stream, @Nonnull String author) {
        checkNotNull(stream, "stream");
        checkNotNull(author, "author");

        try {
            PrettyXmlWriter delegate = new PrettyXmlWriter(newXmlWriter(stream));
            return new DefaultLiquibaseXmlWriter(delegate, new DefaultChangeSetIdGenerator(), author, new DefaultXmlEncoder());
        } catch (XMLStreamException e) {
            throw new LiquibaseDataAccessException("An error occurred while writing to the output stream", e);
        }
    }

    protected XMLStreamWriter newXmlWriter(OutputStream stream) throws XMLStreamException {
        return XMLOutputFactory.newInstance().createXMLStreamWriter(stream, ENCODING);
    }

}

