/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.keycloak.testsuite.util.saml;

import org.keycloak.testsuite.util.SamlClientBuilder;
import org.keycloak.dom.saml.v2.SAML2Object;
import org.keycloak.dom.saml.v2.protocol.ArtifactResolveType;
import org.keycloak.dom.saml.v2.protocol.ArtifactResponseType;
import org.keycloak.dom.saml.v2.protocol.AttributeQueryType;
import org.keycloak.dom.saml.v2.protocol.AuthnRequestType;
import org.keycloak.dom.saml.v2.protocol.LogoutRequestType;
import org.keycloak.dom.saml.v2.protocol.ResponseType;
import org.keycloak.saml.common.constants.GeneralConstants;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.saml.common.util.StaxUtil;
import org.keycloak.saml.processing.core.parsers.saml.SAMLParser;
import org.keycloak.saml.processing.core.saml.v2.writers.SAMLRequestWriter;
import org.keycloak.saml.processing.core.saml.v2.writers.SAMLResponseWriter;
import org.keycloak.testsuite.util.SamlClient.Step;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.stream.XMLStreamWriter;
import org.junit.Assert;
import org.w3c.dom.Document;

/**
 *
 * @author hmlnarik
 */
public abstract class SamlDocumentStepBuilder<T extends SAML2Object, This extends SamlDocumentStepBuilder<T, This>> implements Step {

    @FunctionalInterface
    public interface Saml2ObjectTransformer<T extends SAML2Object> {
        public T transform(T original) throws Exception;
    }

    @FunctionalInterface
    public interface Saml2DocumentTransformer {
        public Document transform(Document original) throws Exception;
    }

    @FunctionalInterface
    public interface StringTransformer {
        public String transform(String original) throws Exception;
    }

    private final SamlClientBuilder clientBuilder;

    private StringTransformer transformer = t -> t;

    public SamlDocumentStepBuilder(SamlClientBuilder clientBuilder) {
        this.clientBuilder = clientBuilder;
    }

    @SuppressWarnings("unchecked")
    public This transformObject(Saml2ObjectTransformer<T> tr) {
        final StringTransformer original = this.transformer;
        this.transformer = s -> {
            final String originalTransformed = original.transform(s);

            if (originalTransformed == null) {
                return null;
            }

            final ByteArrayInputStream baos = new ByteArrayInputStream(originalTransformed.getBytes());
            final T saml2Object = (T) new SAMLParser().parse(baos);
            final T transformed = tr.transform(saml2Object);

            if (transformed == null) {
                return null;
            }

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            XMLStreamWriter xmlStreamWriter = StaxUtil.getXMLStreamWriter(bos);

            if (saml2Object instanceof AuthnRequestType) {
                new SAMLRequestWriter(xmlStreamWriter).write((AuthnRequestType) saml2Object);
            } else if (saml2Object instanceof LogoutRequestType) {
                new SAMLRequestWriter(xmlStreamWriter).write((LogoutRequestType) saml2Object);
            } else if (saml2Object instanceof ArtifactResolveType) {
                new SAMLRequestWriter(xmlStreamWriter).write((ArtifactResolveType) saml2Object);
            } else if (saml2Object instanceof AttributeQueryType) {
                new SAMLRequestWriter(xmlStreamWriter).write((AttributeQueryType) saml2Object);
            } else if (saml2Object instanceof ResponseType) {
                new SAMLResponseWriter(xmlStreamWriter).write((ResponseType) saml2Object);
            } else if (saml2Object instanceof ArtifactResponseType) {
                new SAMLResponseWriter(xmlStreamWriter).write((ArtifactResponseType) saml2Object);
            } else {
                Assert.assertNotNull("Unknown type: <null>", saml2Object);
                Assert.fail("Unknown type: " + saml2Object.getClass().getName());
            }
            return new String(bos.toByteArray(), GeneralConstants.SAML_CHARSET);
        };
        return (This) this;
    }

    public This transformDocument(Saml2DocumentTransformer tr) {
        final StringTransformer original = this.transformer;
        this.transformer = s -> {
            final String originalTransformed = original.transform(s);

            if (originalTransformed == null) {
                return null;
            }

            final Document transformed = tr.transform(DocumentUtil.getDocument(originalTransformed));
            return transformed == null ? null : DocumentUtil.getDocumentAsString(transformed);
        };
        return (This) this;
    }

    public This transformString(StringTransformer tr) {
        final StringTransformer original = this.transformer;
        this.transformer = s -> {
            final String originalTransformed = original.transform(s);

            if (originalTransformed == null) {
                return null;
            }

            return tr.transform(originalTransformed);
        };
        return (This) this;
    }

    public SamlClientBuilder build() {
        return this.clientBuilder;
    }

    public StringTransformer getTransformer() {
        return transformer;
    }
}
