package ru.yandex.webmaster3.validator.xml;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;

import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.webmaster3.core.validator.XmlValidatorSchema;
import ru.yandex.webmaster3.core.validator.XmlValidatorSourceType;
import ru.yandex.webmaster3.core.zora.ZoraForValidatorsService;

/**
 * User: Vladislav Dolbilov (darl@yandex-team.ru)
 * Date: 15.02.12 13:54
 */
public class ValidationSourceResolver {
    private static final Logger log = LoggerFactory.getLogger(ValidationSourceResolver.class);

    @Setter
    private ZoraForValidatorsService zoraForValidatorsService;
    private String xsdDirPath;

    public InputStream[] getSourceInputStreams(String source, XmlValidatorSourceType sourceType, boolean userProxy) {
        log.debug("Source type: " + sourceType);
        log.debug("Source: " + source);
        switch (sourceType) {
            case TEXT:
                //log.debug("temp xsd validation (text): " + name);
                return new InputStream[]{new ByteArrayInputStream(source.getBytes())};
            case URL:
                source = source.trim();
                log.debug(String.format("Requesting url [%s]", source));
                byte[] bytes = zoraForValidatorsService.downloadDocumentGoZora(source);
                return new InputStream[]{new ByteArrayInputStream(bytes)};
            case RESOURCE:
                final String[] schemaNames = XmlValidatorSchema.getSchemaNames(Integer.valueOf(source));
                return Arrays.stream(schemaNames).map(sn -> {
                    try {
                        return new FileInputStream(xsdDirPath + sn);
                    } catch (FileNotFoundException e) {
                        log.error("Unable to find xsd file", e);
                        throw new IllegalStateException(e);
                    }
                }).toArray(InputStream[]::new);
            default:
                throw new IllegalArgumentException("Unknown source type: " + sourceType);
        }
    }

    @Required
    public void setXsdDirPath(String xsdDirPath) {
        this.xsdDirPath = xsdDirPath;
    }

}
