/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *
 */
// https://issues.jboss.org/browse/TEIID-2268
// https://issues.jboss.org/browse/TEIID-2537
// https://issues.jboss.org/browse/TEIID-3016
// https://issues.jboss.org/browse/TEIID-2630
package org.teiid.translator.ws;

import static org.junit.jupiter.api.Assertions.*;

import java.io.ByteArrayInputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.teiid.cdk.CommandBuilder;
import org.teiid.core.types.ClobImpl;
import org.teiid.core.util.ObjectConverterUtil;
import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
import org.teiid.language.Call;
import org.teiid.metadata.MetadataFactory;
import org.teiid.metadata.Procedure;
import org.teiid.query.metadata.SystemMetadata;
import org.teiid.query.metadata.TransformationMetadata;
import org.teiid.query.unittest.RealMetadataFactory;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.WSConnection;

@SuppressWarnings("nls")
public class TestWSTranslator {

	@Test public void testPre81Procedure() throws Exception {
		WSExecutionFactory ef = new WSExecutionFactory();
    	MetadataFactory mf = new MetadataFactory("vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null);
		ef.getMetadata(mf, null);
		Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);
		assertEquals(13, p.getParameters().size());
		p.getParameters().remove(4);  // requestContentType
		p.getParameters().remove(4);  // requestHeaders
		p.getParameters().remove(4);  // failOnHTTPError
		p.getParameters().remove(4);  // stream
		p = mf.getSchema().getProcedure("invoke");
		assertEquals(9, p.getParameters().size());
		p.getParameters().remove(6);  // stream

		TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
		RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
		WSConnection mockConnection = Mockito.mock(WSConnection.class);
		Dispatch<Object> mockDispatch = mockDispatch();
		Mockito.when(mockDispatch.invoke(Mockito.any())).thenReturn(Mockito.mock(DataSource.class));
		Mockito.when(mockConnection.createDispatch(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Service.Mode.class), Mockito.anyBoolean())).thenReturn(mockDispatch);
		CommandBuilder cb = new CommandBuilder(tm);

		Call call = (Call)cb.getCommand("call invokeHttp('GET', null, null)");
		BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
		pe.execute();
		pe.getOutputParameterValues();

		mockConnection = Mockito.mock(WSConnection.class);
		mockDispatch = Mockito.mock(Dispatch.class);
		Mockito.when(mockDispatch.invoke(Mockito.any(StAXSource.class))).thenReturn(Mockito.mock(StAXSource.class));
		Mockito.when(mockConnection.createDispatch(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Service.Mode.class), Mockito.anyBoolean())).thenReturn(mockDispatch);
		call = (Call)cb.getCommand("call invoke()");
		WSProcedureExecution wpe = new WSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
		wpe.execute();
		wpe.getOutputParameterValues();
	}

	@Test public void testStreaming() throws Exception {
		WSExecutionFactory ef = new WSExecutionFactory();
		MetadataFactory mf = new MetadataFactory("vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null);
		ef.getMetadata(mf, null);
		Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);
		assertEquals(13, p.getParameters().size());

		TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
		RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
		WSConnection mockConnection = Mockito.mock(WSConnection.class);
		Dispatch<Object> mockDispatch = mockDispatch();
		DataSource mock = Mockito.mock(DataSource.class);
		ByteArrayInputStream baos = new ByteArrayInputStream(new byte[100]);
		Mockito.when(mock.getInputStream()).thenReturn(baos);
		Mockito.when(mockDispatch.invoke(Mockito.any())).thenReturn(mock);
		Mockito.when(mockConnection.createDispatch(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Service.Mode.class), Mockito.anyBoolean())).thenReturn(mockDispatch);
		CommandBuilder cb = new CommandBuilder(tm);

		Call call = (Call)cb.getCommand("call invokeHttp('GET', null, null, null, null, false, true)");
		BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
		pe.execute();
		List<?> result = pe.getOutputParameterValues();

		Blob b = (Blob) result.get(0);
		assertEquals(100, ObjectConverterUtil.convertToByteArray(b.getBinaryStream()).length);
		try {
			ObjectConverterUtil.convertToByteArray(b.getBinaryStream());
			fail();
		} catch (SQLException e) {
			//should only be able to read once
		}
	}

	@Test public void testHeaders() throws Exception {
		WSExecutionFactory ef = new WSExecutionFactory();
		MetadataFactory mf = new MetadataFactory("vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null);
		ef.getMetadata(mf, null);
		Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);

		TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
		RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
		WSConnection mockConnection = Mockito.mock(WSConnection.class);
		Dispatch<Object> mockDispatch = mockDispatch();
		DataSource mock = Mockito.mock();
		ByteArrayInputStream baos = new ByteArrayInputStream(new byte[100]);
		Mockito.when(mock.getInputStream()).thenReturn(baos);
		Mockito.when(mockDispatch.invoke(Mockito.any())).thenReturn(mock);
		Mockito.when(mockConnection.createDispatch(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Service.Mode.class), Mockito.anyBoolean())).thenReturn(mockDispatch);
		CommandBuilder cb = new CommandBuilder(tm);

		Call call = (Call)cb.getCommand("call invokeHttp('GET', null, null, null, '{\"ContentType\":\"application/json\"}', false, false)");
		BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
		pe.execute();

		Map<String, List<String>> headers = (Map<String, List<String>>) mockDispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
		assertEquals(Arrays.asList("application/json"), headers.get("ContentType"));
	}

	private Dispatch<Object> mockDispatch() {
		Dispatch<Object> mockDispatch = Mockito.mock(Dispatch.class);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(WSConnection.RESPONSE_CODE, 200);
		Map<String, Object> requestMap = new HashMap<String, Object>();
		Mockito.when(mockDispatch.getRequestContext()).thenReturn(requestMap);
		requestMap.put(MessageContext.HTTP_REQUEST_HEADERS, new LinkedHashMap<String, List<String>>());
		Mockito.when(mockDispatch.getResponseContext()).thenReturn(map);
		return mockDispatch;
	}

	@Test public void testJSONHeader() throws Exception {
		HashMap<String, List<String>> vals = new HashMap<String, List<String>>();
		BinaryWSProcedureExecution.parseHeader(vals, new ClobImpl("{\"a\":1, \"b\":[\"x\",\"y\"]}"));
		assertEquals(2, vals.size());
		assertEquals(vals.get("b"), Arrays.asList("x", "y"));
		assertEquals(vals.get("a"), Arrays.asList("1"));
	}

	@Test public void testJSONHeaderInvalid() throws Exception {
		HashMap<String, List<String>> vals = new HashMap<String, List<String>>();
		assertThrows(TranslatorException.class, () -> BinaryWSProcedureExecution.parseHeader(vals, new ClobImpl("[]")));
	}
	
}
