/*
 * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
 *
 * 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.switchyard.component.camel.config.test.v1;

import static junit.framework.Assert.assertTrue;
import static org.apache.camel.util.URISupport.normalizeUri;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

import org.apache.camel.Endpoint;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel;

/**
 * Base test class for camel bindings.
 * 
 * @author Lukasz Dywicki
 *
 * @param <T> Type of model
 * @param <E> Type of endpoint.
 */
public abstract class V1BaseCamelServiceBindingModelTest<T extends V1BaseCamelBindingModel, E extends Endpoint>
    extends V1BaseCamelModelTest<T> {

    private String _fileName;
    private boolean _valid;
    private Class<E> _endpointType;
    private boolean _skipCamelEndpointTesting;

    protected V1BaseCamelServiceBindingModelTest(Class<E> endpointType, String fileName, boolean valid) {
        _endpointType = endpointType;
        _fileName = fileName;
        _valid = valid;
    }

    protected V1BaseCamelServiceBindingModelTest(Class<E> endpointType, String fileName) {
        this(endpointType, fileName, true);
    }

    /**
     * Force test to don't resolve endpoint during the test during 3rd party dependencies
     * ie. registry entries or environment dependencies.
     * 
     * @param skip True if camel context shouldn't create endpoint.
     */
    public void setSkipCamelEndpointTesting(boolean skip) {
        _skipCamelEndpointTesting = skip;
    }

    /**
     * Verify correctness of model read from file.
     * 
     * @throws Exception If model can not be read
     */
    @Test
    public void testFileIsValid() throws Exception {
        validModel(getFirstBinding());
    }

    /**
     * Verify correctness of model created by test.
     * 
     * @throws Exception If model can not be read
     */
    @Test
    public void testModelIsValid() throws Exception {
        validModel(createTestModel());
    }

    /**
     * Verify assertions with file binding.
     * 
     * @throws Exception If model from file can not be read.
     */
    @Test
    public void testModelAssertionsFromFile() throws Exception {
        createModelAssertions(getFirstBinding());
    }

    /**
     * Verify assertions with model binding.
     */
    @Test
    public void testModelAssertionsFromModel() {
        createModelAssertions(createTestModel());
    }

    /**
     * Verify if model from file is similar to model created by test.
     * 
     * @throws Exception If model from file can not be read.
     */
    @Test
    public void testSimilarityBetweenFileAndModel() throws Exception {
        String refXml = getFirstBinding().toString();
        String newXml = createTestModel().toString();
        XMLUnit.setIgnoreWhitespace(true);
        Diff diff = XMLUnit.compareXML(refXml, newXml);
        if (!diff.similar()) {
            System.out.println("Expected\n" + refXml);
            System.out.println("Generated\n" + newXml);
        }
        assertTrue(diff.toString(), diff.similar());
    }

    /**
     * This test verify if uri reported by test is same as generated by camel
     * endpoint.
     * 
     * To avoid problems with parameter order in query string uri is normalized
     * before comparision.
     * 
     * @throws Exception An exception might be thrown when test is failing.
     */
    @Test
    public void testCamelEndpointUriFromModel() throws Exception {
        verifyCamelEndpointUri(createTestModel());
    }

    /**
     * This test verify if uri of binding read from file is same as generated by camel
     * endpoint.
     * 
     * To avoid problems with parameter order in query string uri is normalized
     * before comparision.
     * 
     * @throws Exception An exception might be thrown when test is failing.
     */
    @Test
    public void testCamelEndpointUriFromFile() throws Exception {
        verifyCamelEndpointUri(getFirstBinding());
    }

    /**
     * Verify if uri generated by model binding is equals to uri produced by test.
     * 
     * @throws Exception Any exception can be thrown from uri normalization code.
     */
    @Test
    public void verifyModelUri() throws Exception {
        String componentURI = createTestModel().getComponentURI().toString();

        assertUriEquals(createEndpointUri(), normalizeUri(componentURI));
    }

    protected void validModel(T model) {
        if (_valid) {
            model.assertModelValid();
        } else {
            try {
                model.assertModelValid();
                fail("Expected invalid model, but validation framework did not report any problems");
            } catch (Exception e) {
                e.getMessage(); // everything ok - model is invalid
            }
        }
    }

    protected void verifyCamelEndpointUri(T model) {
        if (_skipCamelEndpointTesting) {
            return;
        }

        assertUriEquals(createEndpointUri(), getEndpoint(model, _endpointType).getEndpointUri());
    }

    /**
     * Verify if given parameter is equals to expected value.
     * 
     * NOTE: expected uri is normalized before comparision, given uri should be
     * normalized by caller.
     * 
     * @param expected Expected uri.
     * @param given Given uri, after normalization done by camel.
     */
    protected void assertUriEquals(String expected, String given) {
        try {
            assertEquals(normalizeUri(expected), given);
        } catch (UnsupportedEncodingException e) {
            throw new Error("Unsuported encoding", e);
        } catch (URISyntaxException e) {
            throw new Error("Uri syntax is invalid", e);
        }
    }

    protected T getFirstBinding() throws Exception {
        return getFirstCamelBinding(_fileName);
    }

    protected abstract String createEndpointUri();
    protected abstract void createModelAssertions(T model);
    protected abstract T createTestModel();

    protected Class<E> getEndpointType() {
        return _endpointType;
    }

    protected String getFileName() {
        return _fileName;
    }

}
