// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package jodd.db.oom;

import jodd.db.DbOom;
import jodd.db.DbSession;
import jodd.db.oom.fixtures.Tester;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

/**
 * Live database test. Requires database services to be started.
 */
class LiveDatabaseTest extends DbBaseTest {

	/**
	 * DATABASES TO TEST!
	 */
	DbAccess[] databases = new DbAccess[]{
				new MySql(),
				new PostgreSql(),
				new HsqlDb(),
				//new MsSqlDb(),
		};

	/**
	 * MySql.
	 */
	class MySql extends MySqlDbAccess {

		@Override
		public String createTableSql() {
			return "create table TESTER (" +
						"ID			INT UNSIGNED NOT NULL AUTO_INCREMENT," +
						"NAME		VARCHAR(20)	not null," +
						"VALUE		INT NULL," +
						"primary key (ID)" +
						')';
		}

		@Override
		public String getTableName() {
			return "TESTER";
		}
	}

	/**
	 * PostgreSql.
	 */
	class PostgreSql extends PostgreSqlDbAccess {

		@Override
		public String createTableSql() {
			return "create table TESTER (" +
						"ID			SERIAL," +
						"NAME		varchar(20)	NOT NULL," +
						"VALUE		integer NULL," +
						"primary key (ID)" +
						')';
		}

		@Override
		public String getTableName() {
			return "TESTER";
		}
	}

	/**
	 * MsSql.
	 */
	class MsSqlDb extends MsSqlDbAccess {

		@Override
		public String createTableSql() {
			return "create table TESTER (" +
				"ID			INT NOT NULL IDENTITY PRIMARY KEY," +
				"NAME		varchar(20)	NOT NULL," +
				"VALUE		int NULL" +
				')';
		}

		@Override
		public String getTableName() {
			return "TESTER";
		}
	}

	/**
	 * HsqlDB.
	 */
	class HsqlDb extends HsqlDbAccess {

		@Override
		public String createTableSql() {
			return "create table TESTER (" +
						"ID			integer GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY," +
						"NAME		varchar(20)	NOT NULL," +
						"VALUE		integer NULL" +
						')';
		}

		@Override
		public String getTableName() {
			return "TESTER";
		}
	}

	// ---------------------------------------------------------------- test

	@Test
	void testLiveDb() {
		for (DbAccess db : databases) {
			System.out.println("\t" + db.getClass().getSimpleName());
			init(db);

			DbOom.get().entityManager().registerEntity(Tester.class);

			db.createTables();

			try {
				workoutEntity();
			} finally {
				db.close();
			}
		}
	}

	// ---------------------------------------------------------------- workout

	protected void workoutEntity() {
		DbSession session = new DbSession(connectionPool);

		Tester tester = new Tester();
		tester.setName("one");
		tester.setValue(Integer.valueOf(7));

		DbOomQuery dbOomQuery = DbOomQuery.query(session, dbOom.entities().insert(tester));
		dbOomQuery.setGeneratedKey();
		dbOomQuery.executeUpdate();
		assertDb(session, "{1,one,7}");

		long key = dbOomQuery.getGeneratedKey();
		tester.setId(Long.valueOf(key));
		dbOomQuery.close();

		assertEquals(1, tester.getId().longValue());

		tester.setName("seven");
		DbOomQuery.query(session, dbOom.entities().updateAll(tester)).executeUpdate();
		assertDb(session, "{1,seven,7}");

		tester.setName("SEVEN");
		DbOomQuery.query(session, dbOom.entities().update(tester)).executeUpdate();
		assertDb(session, "{1,SEVEN,7}");

		tester.setName("seven");
		DbOomQuery.query(session, dbOom.entities().updateColumn(tester, "name")).executeUpdate();
		assertDb(session, "{1,seven,7}");

		tester = new Tester();
		tester.setId(Long.valueOf(2));
		tester.setName("two");
		tester.setValue(Integer.valueOf(2));
		DbOomQuery.query(session, dbOom.entities().insert(tester)).executeUpdate();
		assertDb(session, "{1,seven,7}{2,two,2}");

		long count = DbOomQuery.query(session, dbOom.entities().count(Tester.class)).executeCount();
		assertEquals(2, count);

		tester = DbOomQuery.query(session, dbOom.entities().findById(Tester.class, 2)).find(Tester.class);
		assertNotNull(tester);
		assertEquals("{2,two,2}", tester.toString());

		tester = DbOomQuery
				.query(session, dbOom.entities()
						.findById(Tester.class, 2)
						.aliasColumnsAs(ColumnAliasType.COLUMN_CODE))
				.find(Tester.class);
		assertNotNull(tester);
		assertEquals("{2,two,2}", tester.toString());

		tester = DbOomQuery
				.query(session, dbOom.entities()
						.findById(Tester.class, 2)
						.aliasColumnsAs(ColumnAliasType.TABLE_REFERENCE))
				.find(Tester.class);
		assertNotNull(tester);
		assertEquals("{2,two,2}", tester.toString());

		tester = DbOomQuery
				.query(session, dbOom.entities()
						.findById(Tester.class, 2)
						.aliasColumnsAs(ColumnAliasType.TABLE_NAME))
				.find(Tester.class);
		assertNotNull(tester);
		assertEquals("{2,two,2}", tester.toString());

		tester = DbOomQuery
				.query(session, dbOom.entities()
						.findById(Tester.class, 2)
						.aliasColumnsAs(ColumnAliasType.COLUMN_CODE))    // fixes POSTGRESQL
				.find();
		assertEquals("{2,two,2}", tester.toString());

		tester = new Tester();
		tester.setName("seven");
		tester = DbOomQuery.query(session, dbOom.entities().find(tester)).find(Tester.class);
		assertEquals("{1,seven,7}", tester.toString());

		DbOomQuery.query(session, dbOom.entities().findByColumn(Tester.class, "name", "seven")).find(Tester.class);
		assertEquals("{1,seven,7}", tester.toString());

		DbOomQuery.query(session, dbOom.entities().deleteById(Tester.class, 1)).executeUpdate();

		count = DbOomQuery.query(session, dbOom.entities().count(Tester.class)).executeCount();
		assertEquals(1, count);

		session.closeSession();
	}

	// ---------------------------------------------------------------- util

	protected void assertDb(final DbSession dbSession, final String expected) {
		DbOomQuery query = DbOomQuery.query(dbSession, "select * from TESTER order by ID");
		List<Tester> testerList = query.list(Tester.class);

		StringBuilder sb = new StringBuilder();
		for (Tester tester : testerList) {
			sb.append(tester.toString());
		}

		assertEquals(expected, sb.toString());
	}

}
