/*
 * 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-3519
package org.teiid.systemmodel;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.teiid.core.util.UnitTestUtil;
import org.teiid.jdbc.FakeServer;
import org.teiid.jdbc.FakeServer.DeployVDBParameter;
import org.teiid.metadata.*;
import org.teiid.metadata.TableStats;
import org.teiid.metadata.Table.TriggerEvent;

@SuppressWarnings("nls")
public class TestMetadataUpdates {
	
	// BUG locale issues
	// SOLUTION use fix english locale for test data
	// FIXED by aklebeck
	// date 21.05.2012
	static {
		Locale.setDefault(Locale.ENGLISH);
	}
	// BUG end

	// EXTENSION
	// ISSUE: DVCORE-2441
	// FIXED BY: Roman Pedchenko
	// DATE: 2014.10.23
	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
	// static Connection connection;
	Connection connection;
	// END EXTENSION
    
    static final String VDB = "metadata";
    
    // EXTENSION
    // ISSUE: DVCORE-2441
    // FIXED BY: Roman Pedchenko
    // DATE: 2014.10.23
    // ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
    private static FakeServer server;

    // END EXTENSION
	// BUG: the correct execution of tests depended on the order they were executed. If testAlterView() was executed
	// before testViewMetadataRepositoryMerge(), the second test failed because the source view was altered by the first
	// one
	// ISSUE: DV-28
	// SOLUTION: 1) added a counter to deploy a VDB with a different name for each test;
	// 2) used the counter in setUp() method and changed the Junit annotation (old:@BeforeAll - new:@BeforeEach) in order
	// to recreate the server before the execution of each test and avoid cache problems with indexes
	// 3) changed the Junit annotation for the tearDown() method (old:@AfterAll - new:@AfterEach) in order to close the
	// connection after each test
	// FIXED by Salvatore Raunich
	// date 08.08.2012
	static int counter = 0;
	// EXTENSION
	// ISSUE: DVCORE-2441
	// FIXED BY: Roman Pedchenko
	// DATE: 2014.10.23
	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
	// BUG END
	@BeforeAll public static void oneTimeSetUp() throws Exception {
    	server = new FakeServer(true);    	
	}
	// END EXTENSION

	// EXTENSION
	// ISSUE: DVCORE-2441
	// FIXED BY: Roman Pedchenko
	// DATE: 2014.10.23
	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
	// @BeforeEach
	// public void setUp() throws Exception {
	// 	FakeServer server = new FakeServer(true);
	// 	server.deployVDB(VDB + counter, UnitTestUtil.getTestDataPath() + "/metadata.vdb", new DeployVDBParameter(null, getMetadataRepo()));
	// 	connection = server.createConnection("jdbc:datavirtuality:" + VDB + counter++); //$NON-NLS-1$ //$NON-NLS-2$		
	@AfterAll public static void oneTimeTearDown() throws Exception {
		server.stop();
	// END EXTENSION
	}
    // EXTENSION
    // ISSUE: DVCORE-2441
    // FIXED BY: Roman Pedchenko
    // DATE: 2014.10.23
    // ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
    // // BUG END
	
	@BeforeEach public void setup() throws Exception {
		server.undeployVDB(VDB);
		server.deployVDB(VDB, UnitTestUtil.getTestDataPath() + "/metadata.vdb", new DeployVDBParameter(null, getMetadataRepo()));
		connection = server.createConnection("jdbc:datavirtuality:" + VDB); //$NON-NLS-1$ //$NON-NLS-2$		
	}
	
    @AfterEach public void tearDown() throws SQLException {
	    if (connection != null) {
		    connection.close();
	    }
    }
    // END EXTENSION

	private static DefaultMetadataRepository getMetadataRepo() {
		// EXTENSION
		// ISSUE: DVCORE-2441
		// FIXED BY: Roman Pedchenko
		// DATE: 2014.10.26
		// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-2235, 2661, 2178, 2297
		// DefaultMetadataRepository repo = Mockito.mock(DefaultMetadataRepository.class);
		// Mockito.stub(repo.getViewDefinition(Mockito.anyString(), Mockito.anyInt(), (Table)Mockito.anyObject())).toAnswer(new Answer<String>() {
		// 	@Override
		// 	public String answer(InvocationOnMock invocation) throws Throwable {
		// 		Table t = (Table)invocation.getArguments()[2];
		// 		if (t.getName().equals("vw")) {
		DefaultMetadataRepository repo = new DefaultMetadataRepository() {

			@Override
			public void setColumnStats(String vdbName, int vdbVersion,
					Column column, ColumnStats columnStats) {
				
			}

			@Override
			public void setInsteadOfTriggerDefinition(String vdbName,
					int vdbVersion, Table table, TriggerEvent triggerOperation,
					String triggerDefinition) {
				
			}

			@Override
			public void setInsteadOfTriggerEnabled(String vdbName,
					int vdbVersion, Table table, TriggerEvent triggerOperation,
					boolean enabled) {
				
			}

			@Override
			public void setProcedureDefinition(String vdbName, int vdbVersion,
					Procedure procedure, String procedureDefinition) {
				
			}

			@Override
			public void setFunctionDefinition(String vdbName, int vdbVersion,
											  FunctionMethod function, String functionDefinition) {

			}

			@Override
			public void setProperty(String vdbName, int vdbVersion,
					AbstractMetadataRecord record, String name, String value) {
				
			}

			@Override
			public void setTableStats(String vdbName, int vdbVersion,
					Table table, TableStats tableStats) {
				
			}

			@Override
			public void setViewDefinition(String vdbName, int vdbVersion,
					Table table, String viewDefinition) {
				
			}
			
			@Override
			public String getViewDefinition(String vdbName, int vdbVersion,
					Table table) {
				if (table.getName().equals("vw")) {
		// END EXTENSION
    				return "select '2011'";
    			}
    			return null;
    	// EXTENSION
    	// ISSUE: DVCORE-2441
    	// FIXED BY: Roman Pedchenko
    	// DATE: 2014.10.26
    	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-2235, 2661, 2178, 2297
    	// 	}
    	// });
    	// Mockito.stub(repo.getProcedureDefinition(Mockito.anyString(), Mockito.anyInt(), (Procedure)Mockito.anyObject())).toAnswer(new Answer<String>() {
    	// 	@Override
    	// 	public String answer(InvocationOnMock invocation) throws Throwable {
    	// 		Procedure t = (Procedure)invocation.getArguments()[2];
    	// 		if (t.getName().equals("proc")) {
			}
			
			@Override
			public String getProcedureDefinition(String vdbName,
					int vdbVersion, Procedure procedure) {
    			if (procedure.getName().equals("proc")) {
    	// END EXTENSION
    				return "create virtual procedure begin select '2011'; if ((call isLoggable())) call logMsg(msg=>'hello'); end";
    			}
    			return null;
    	// EXTENSION
    	// ISSUE: DVCORE-2441
    	// FIXED BY: Roman Pedchenko
    	// DATE: 2014.10.26
    	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-2235, 2661, 2178, 2297
    	// 	}
    	// });
    	// Mockito.stub(repo.getInsteadOfTriggerDefinition(Mockito.anyString(), Mockito.anyInt(), (Table)Mockito.anyObject(), (Table.TriggerEvent) Mockito.anyObject())).toAnswer(new Answer<String>() {
    	// 	@Override
    	// 	public String answer(InvocationOnMock invocation) throws Throwable {
			}
			
			@Override
			public String getInsteadOfTriggerDefinition(String vdbName,
					int vdbVersion, Table table, TriggerEvent triggerOperation) {
    	// END EXTENSION
				return "for each row select 1/0;";
    	// EXTENSION
    	// ISSUE: DVCORE-2441
    	// FIXED BY: Roman Pedchenko
    	// DATE: 2014.10.26
    	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-2235, 2661, 2178, 2297
    	// 	}
    	// });
    	// Mockito.stub(repo.isInsteadOfTriggerEnabled(Mockito.anyString(), Mockito.anyInt(), (Table)Mockito.anyObject(), (Table.TriggerEvent) Mockito.anyObject())).toAnswer(new Answer<Boolean>() {
    	// 	@Override
    	// 	public Boolean answer(InvocationOnMock invocation) throws Throwable {
			}
			
			@Override
			public Boolean isInsteadOfTriggerEnabled(String vdbName,
					int vdbVersion, Table table, TriggerEvent triggerOperation) {
    	// END EXTENSION
				return Boolean.TRUE;
			}
		};
    	return repo;
	}
    
    @Test public void testViewMetadataRepositoryMerge() throws Exception {
    	Statement s = connection.createStatement();
    	ResultSet rs = s.executeQuery("select * from vw");
    	rs.next();
    	assertEquals(2011, rs.getInt(1));
    }
    
    @Test public void testViewUpdateMetadataRepositoryMerge() throws Exception {
    	Statement s = connection.createStatement();
	    assertThrows(SQLException.class, () -> s.execute("delete from vw"));
    }
    
    @Test public void testProcMetadataRepositoryMerge() throws Exception {
    	Statement s = connection.createStatement();
    	ResultSet rs = s.executeQuery("call proc(1)");
    	rs.next();
    	assertEquals(2011, rs.getInt(1));
    }
    
    @Test public void testSetProperty() throws Exception {
    	CallableStatement s = connection.prepareCall("{? = call sysadmin.setProperty((select uid from tables where name='vw'), 'foo', 'bar')}");
    	assertFalse(s.execute());
    	assertNull(s.getClob(1));
    	
    	Statement stmt = connection.createStatement();
    	ResultSet rs = stmt.executeQuery("select name, \"value\" from properties where uid = (select uid from tables where name='vw')");
    	rs.next();
    	assertEquals("foo", rs.getString(1));
    	assertEquals("bar", rs.getString(2));
    }
    
    @Test public void testSetProperty_Invalid() throws Exception {
    	CallableStatement s = connection.prepareCall("{? = call sysadmin.setProperty('ah', 'foo', 'bar')}");
	    assertThrows(SQLException.class, () -> s.execute());
    }
    
    @Test public void testAlterView() throws Exception {
    	Statement s = connection.createStatement();
    	ResultSet rs = s.executeQuery("select * from vw");
    	rs.next();
    	assertEquals(2011, rs.getInt(1));
    	
    	assertFalse(s.execute("alter view vw as select '2012'"));
    	
    	rs = s.executeQuery("select * from vw");
    	rs.next();
    	assertEquals(2012, rs.getInt(1));
    }
    
	@Test
	// BUG: this test passes if executed as a standalone but it randomly fails if executed after another one. It also
	// randomly fails if executed iteratively in a loop.
	// ISSUE: DV-28
	// SOLUTION: no solution
	// FIXED by Salvatore Raunich
	// date 08.08.2012

	// BUG: The bug in DV-28 was fixed in Teiid 8.1.
	// ISSUE: DV-30
	// SOLUTION: removed "ignore" annotation
	// FIXED by Salvatore Raunich
	// date 09.01.2013
	public void testAlterProcedure() throws Exception {
		Statement s = connection.createStatement();
		ResultSet rs = s.executeQuery("call proc(1)");
		rs.next();
    	// EXTENSION
    	// ISSUE: DVCORE-2441
    	// FIXED BY: Roman Pedchenko
    	// DATE: 2014.10.23
    	// ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
    	// assertEquals(2011, rs.getInt(1));
    	// 
    	// assertFalse(s.execute("alter procedure proc as begin select '2012'; end"));
    	// 
    	// // the sleep is needed to ensure that the plan is invalidated
		Thread.sleep(200);
    	assertEquals(2011, rs.getInt(1));
    	
    	assertFalse(s.execute("alter procedure proc as begin select '2012'; end"));
    	//the sleep is needed to ensure that the plan is invalidated
    	Thread.sleep(100); 
    	
    	// END EXTENSION
		rs = s.executeQuery("call proc(1)");
		rs.next();
		assertEquals(2012, rs.getInt(1));
	}
	// BUG END
    
    @Test public void testAlterTriggerActionUpdate() throws Exception {
    	Statement s = connection.createStatement();
    	try {
    		s.execute("update vw set x = 1");
    		fail();
    	} catch (SQLException e) {
    	}
    	
    	assertFalse(s.execute("alter trigger on vw instead of update as for each row select 1;"));
    	
    	s.execute("update vw set x = 1");
    	assertEquals(1, s.getUpdateCount());
    }
    
    @Test public void testAlterTriggerActionInsert() throws Exception {
    	Statement s = connection.createStatement();
    	try {
    		s.execute("insert into vw (x) values ('a')");
    		fail();
    	} catch (SQLException e) {
    	}
    	
    	assertFalse(s.execute("alter trigger on vw instead of insert as for each row select 1;"));
    	
    	s.execute("insert into vw (x) values ('a')");
    	assertEquals(1, s.getUpdateCount());
    }
    
    @Test public void testAlterTriggerActionDelete() throws Exception {
    	Statement s = connection.createStatement();
    	try {
    		s.execute("delete from vw");
    		fail();
    	} catch (SQLException e) {
    	}
    	
    	assertFalse(s.execute("alter trigger on vw instead of delete as for each row select 1;"));
    	
    	s.execute("delete from vw");
    	assertEquals(1, s.getUpdateCount());
    	
    	assertFalse(s.execute("alter trigger on vw instead of delete disabled"));
    	
    	try {
    		s.execute("delete from vw");
    		fail();
    	} catch (SQLException e) {
    	}
    	
    	assertFalse(s.execute("alter trigger on vw instead of delete enabled"));
    	
    	s.execute("delete from vw");
    	assertEquals(1, s.getUpdateCount());
    }
    
    @Test public void testCreateTriggerActionUpdate() throws Exception {
    	Statement s = connection.createStatement();
	    assertThrows(SQLException.class, () -> s.execute("create trigger on vw instead of update as for each row select 1;"));
    }
    
}
