/*
 * 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-2422
// https://issues.jboss.org/browse/TEIID-3282
// https://issues.jboss.org/browse/TEIID-4567
// https://issues.jboss.org/browse/TEIID-4532
// https://issues.jboss.org/browse/TEIID-3530
// https://issues.jboss.org/browse/TEIID-3491
// https://issues.redhat.com/browse/TEIID-3502
package org.teiid.query.function;

import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.core.types.BinaryType;
import org.teiid.core.types.ClobImpl;
import org.teiid.core.types.ClobType;
import org.teiid.core.util.PropertiesUtils;
import org.teiid.core.util.TimestampWithTimezone;
import org.teiid.language.SQLConstants.NonReserved;
import org.teiid.query.processor.TestProcessor;
import org.teiid.query.unittest.TimestampUtil;
import org.teiid.query.util.CommandContext;
import org.teiid.translator.SourceSystemFunctions;

import java.sql.Timestamp;
import java.util.TimeZone;

import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.*;
@SuppressWarnings("nls")
public class TestFunctionMethods {

	@BeforeAll public static void oneTimeSetup() {
		TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-0600"));
	}

	@AfterAll public static void oneTimeTearDown() {
		TimestampWithTimezone.resetCalendar(null);
	}

	@Test public void testUnescape() {
		assertEquals("a\t\n\n%6", FunctionMethods.unescape("a\\t\\n\\012\\456"));
	}

	@Test public void testUnescape1() {
		assertEquals("a\u45AA'", FunctionMethods.unescape("a\\u45Aa\'"));
	}

	@Test public void testIso8601Week() {
		assertEquals(53, FunctionMethods.week(TimestampUtil.createDate(105, 0, 1)));
	}

	@Test public void testIso8601Week1() {
		assertEquals(52, FunctionMethods.week(TimestampUtil.createDate(106, 0, 1)));
	}

	@Test public void testDayOfWeek() {
		assertEquals(2, FunctionMethods.dayOfWeek(TimestampUtil.createDate(111, 10, 28)));
	}

	@Test public void testTimestampDiffTimeStamp_ErrorUsingEndDate2304() throws Exception {
		assertEquals(Long.valueOf(106753), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_DAY,
				new Timestamp(TimestampUtil.createDate(112, 0, 1).getTime()),
				new Timestamp(TimestampUtil.createDate(404, 3, 13).getTime()), false));
	}

	@Test public void testTimestampDiffTimeStamp_ErrorUsingEndDate2304a() throws Exception {
		assertEquals(Long.valueOf(32244), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_DAY,
				new Timestamp(TimestampUtil.createDate(112, 0, 1).getTime()),
				new Timestamp(TimestampUtil.createDate(200, 3, 13).getTime()), true));
	}

	@Test public void testTimestampDiffCalendarBasedHour() throws Exception {
		assertEquals(Long.valueOf(2562072), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_HOUR,
				new Timestamp(TimestampUtil.createDate(112, 0, 1).getTime()),
				new Timestamp(TimestampUtil.createDate(404, 3, 13).getTime()), true));
	}

	@Test public void testTimestampDiffCalendarBasedHour1() throws Exception {
		TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("America/New York"));
		try {
			assertEquals(Long.valueOf(2472), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_HOUR,
				new Timestamp(TimestampUtil.createDate(112, 0, 1).getTime()),
				new Timestamp(TimestampUtil.createDate(112, 3, 13).getTime()), true));
		} finally {
			TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-0600"));
		}
	}

	@Test public void testTimestampDiffCalendarBasedMonth() throws Exception {
		assertEquals(Long.valueOf(1), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_MONTH,
				new Timestamp(TimestampUtil.createDate(112, 0, 10).getTime()),
				new Timestamp(TimestampUtil.createDate(112, 1, 1).getTime()), true));
	}

	@Test public void testTimestampDiffCalendarBasedWeek() throws Exception {
		assertEquals(Long.valueOf(1), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_WEEK,
				new Timestamp(TimestampUtil.createDate(113, 2, 2).getTime()),
				new Timestamp(TimestampUtil.createDate(113, 2, 3).getTime()), true));
	}

	@Test public void testTimestampDiffCalendarBasedWeek1() throws Exception {
		assertEquals(Long.valueOf(0), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_WEEK,
				new Timestamp(TimestampUtil.createDate(113, 2, 3).getTime()),
				new Timestamp(TimestampUtil.createDate(113, 2, 4).getTime()), true));
	}

	@Test public void testTimestampDiffCalendarBasedWeek2() throws Exception {
		assertEquals(Long.valueOf(0), FunctionMethods.timestampDiff(NonReserved.SQL_TSI_WEEK,
				new Timestamp(TimestampUtil.createDate(113, 2, 4).getTime()),
				new Timestamp(TimestampUtil.createDate(113, 2, 3).getTime()), true));
    }

	@Test public void dateTrunkOk() {
		assertEquals("1987-01-01 00:00:00.0", FunctionMethods.truncDateImpl("DAY", "1987-01-01 22:22:22.222"));
		assertEquals("1987-02-28 00:00:00.0", FunctionMethods.truncDateImpl("DAY", "1987-02-28 22:22:22.222"));
		assertEquals("1987-05-01 00:00:00.0", FunctionMethods.truncDateImpl("DAY", "1987-05-01 22:22:22.222"));

		// century and millennium end with 1 - See stress tests
		assertEquals("1001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1987-05-01 22:22:22.222"));
		assertEquals("1901-01-01 00:00:00.0", FunctionMethods.truncDateImpl("CENTURY", "1987-05-01 22:22:22.222"));
		assertEquals("1980-01-01 00:00:00.0", FunctionMethods.truncDateImpl("DECADE", "1987-05-01 22:22:22.222"));
		assertEquals("1987-01-01 00:00:00.0", FunctionMethods.truncDateImpl("YEAR", "1987-05-01 22:22:22.222"));
		assertEquals("1987-05-01 00:00:00.0", FunctionMethods.truncDateImpl("MONTH", "1987-05-01 22:22:22.222"));
		assertEquals("1987-05-01 22:00:00.0", FunctionMethods.truncDateImpl("HOUR", "1987-05-01 22:22:22.222"));
		assertEquals("1987-05-01 22:22:00.0", FunctionMethods.truncDateImpl("MINUTE", "1987-05-01 22:22:22.222"));
		assertEquals("1987-05-01 22:22:22.0", FunctionMethods.truncDateImpl("SECOND", "1987-05-01 22:22:22.123456789"));
		assertEquals("1987-05-01 22:22:22.123", FunctionMethods.truncDateImpl("MILLISECOND", "1987-05-01 22:22:22.123456789"));
		assertEquals("1987-05-01 22:22:22.123456", FunctionMethods.truncDateImpl("MICROSECOND", "1987-05-01 22:22:22.123456789"));
		assertEquals("1987-05-01 22:22:22.123456789", FunctionMethods.truncDateImpl("NANOSECOND", "1987-05-01 22:22:22.123456789"));

		// Test quarter
		assertEquals("1987-01-01 00:00:00.0", FunctionMethods.truncDateImpl("QUARTER", "1987-03-01 22:22:22.123456789"));
		assertEquals("1987-04-01 00:00:00.0", FunctionMethods.truncDateImpl("QUARTER", "1987-06-01 22:22:22.123456789"));
		assertEquals("1987-07-01 00:00:00.0", FunctionMethods.truncDateImpl("QUARTER", "1987-09-01 22:22:22.123456789"));
		assertEquals("1987-10-01 00:00:00.0", FunctionMethods.truncDateImpl("QUARTER", "1987-12-11 22:22:22.123456789"));

		// Test week
		assertEquals("2023-03-13 00:00:00.0", FunctionMethods.truncDateImpl("WEEK", "2023-03-16 22:22:22.123456789"));
		assertEquals("1987-12-07 00:00:00.0", FunctionMethods.truncDateImpl("WEEK", "1987-12-11 22:22:22.123456789"));
		assertEquals("1987-12-14 00:00:00.0", FunctionMethods.truncDateImpl("WEEK", "1987-12-20 22:22:22.123456789"));
		assertEquals("1987-12-21 00:00:00.0", FunctionMethods.truncDateImpl("WEEK", "1987-12-27 22:22:22.123456789"));
		assertEquals("1987-12-28 00:00:00.0", FunctionMethods.truncDateImpl("WEEK", "1987-12-31 22:22:22.123456789"));

		// Stress tests
		assertEquals("0001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1000-05-01 22:22:22.222"));
		assertEquals("0901-01-01 00:00:00.0", FunctionMethods.truncDateImpl("CENTURY", "1000-05-01 22:22:22.222"));

		// Test other formats
		assertEquals("1001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1234-05-11 21:15:42"));
		assertEquals("1001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1234-05-11 21:15"));
		assertEquals("1001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1234-05-11 21"));
		assertEquals("1001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1234-05-11 "));
		assertEquals("1001-01-01 00:00:00.0", FunctionMethods.truncDateImpl("MILLENNIUM", "1234-05-11"));
	}

	@Test public void regexpReplaceOkay() throws Exception {
		assertEquals(
				"fooXbaz",
				FunctionMethods.regexpReplace(null, "foobarbaz", "b..", "X")
		);
		assertEquals(
				"fooXX",
				FunctionMethods.regexpReplace(null, "foobarbaz", "b..", "X", "g")
		);
		assertEquals(
				"fooXarYXazY",
				FunctionMethods.regexpReplace(null, "foobarbaz", "b(..)", "X$1Y", "g")
		);
		assertEquals(
				"fooBXRbXz",
				FunctionMethods.regexpReplace(null, "fooBARbaz", "a", "X", "gi")
		);
	}

	@Test
	public void regexpInvalidFlagsBad() throws Exception {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.regexpReplace(null, "foobarbaz", "b..", "X", "y"));
	}

	@Test public void testAbsIntBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.abs(Integer.MIN_VALUE));
	}

	@Test public void testAbsLongBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.abs(Long.MIN_VALUE));
	}

	@Test public void testPlusLongBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.plus(Long.MIN_VALUE, -1));
	}

	@Test public void testPlusLongBounds1() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.plus(Long.MAX_VALUE, 1));
	}

	@Test public void testPlusIntBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.plus(Integer.MIN_VALUE, -1));
	}

	@Test public void testPlusIntBounds1() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.plus(Integer.MAX_VALUE, 1));
	}

	@Test public void testMinusIntBounds1() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.minus(Integer.MAX_VALUE, -1));
	}

	@Test public void testMinusLongBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.minus(Long.MIN_VALUE, 1));
	}

	@Test public void testMinusLongBounds1() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.minus(Long.MAX_VALUE, -1));
	}

	@Test public void testMinusIntBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.minus(Integer.MIN_VALUE, 1));
	}

	@Test public void testDivideIntBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.divide(Integer.MIN_VALUE, -1));
	}

	@Test public void testDivedLongBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.divide(Long.MIN_VALUE, -1));
	}

	@Test public void testMultLongBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.multiply(Long.MIN_VALUE, -1));
	}

	@Test public void testMultLongBounds1() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.multiply(Long.MAX_VALUE, 2));
	}

	@Test public void testMultLongBounds2() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.multiply(Long.MIN_VALUE, -2));
	}

	@Test public void testMultIntBounds() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.multiply(Integer.MIN_VALUE, -1));
	}

	@Test public void testMultIntBounds1() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.multiply(Integer.MAX_VALUE, 2));
	}

	@Test public void testMultIntBounds2() throws FunctionExecutionException {
		assertThrows(FunctionExecutionException.class, () -> FunctionMethods.multiply(Integer.MIN_VALUE, -2));
	}

    @Test
    public void testUpperLowerClob() throws Exception {
        char[] val = new char[] {87, 122, 147, 0xD801, 0xDC37};

        assertEquals(new String(val).toUpperCase(), ClobType.getString(FunctionMethods.upperCase(new ClobType(ClobImpl.createClob(val)))));
        assertEquals(new String(val).toLowerCase(), ClobType.getString(FunctionMethods.lowerCase(new ClobType(ClobImpl.createClob(val)))));
    }

	@Test public void testHashes() throws Exception {
		assertEquals("900150983CD24FB0D6963F7D28E17F72", PropertiesUtils.toHex(FunctionMethods.md5_binary("abc").getBytesDirect()));
		assertEquals("A9993E364706816ABA3E25717850C26C9CD0D89D", PropertiesUtils.toHex(FunctionMethods.sha1("abc").getBytesDirect()));
		assertEquals("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD", PropertiesUtils.toHex(FunctionMethods.sha2_256("abc").getBytesDirect()));
		assertEquals("DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F", PropertiesUtils.toHex(FunctionMethods.sha2_512("abc").getBytesDirect()));
	}

	/*@Test public void testSomething() throws FunctionExecutionException {
		System.out.println(FunctionMethods.regexpReplace(TestProcessor.createCommandContext(), "Goodbye World", "[g-o].", "x", "gi"));
	}*/

	@Test
	public void testTruncDateWithTimestamp() throws Exception {
		CommandContext ctx = new CommandContext();
		String datePart = "MONTH";
		Timestamp input = Timestamp.valueOf("2025-11-12 15:23:42");

		Timestamp result = FunctionMethods.truncDate(ctx, datePart, input);

		assertEquals(Timestamp.valueOf("2025-11-01 00:00:00.0"), result);
	}

	@Test
	public void testTruncDateWithString() throws Exception {
		CommandContext ctx = new CommandContext();
		String datePart = "YEAR";
		String input = "2025-31-12 15:23:42.0";

		Timestamp result = FunctionMethods.truncDate(ctx, datePart, input);

		assertEquals(Timestamp.valueOf("2025-01-01 00:00:00.0"), result);
	}

	@Test
	public void testTruncDateInvalidParamCount() {
		CommandContext ctx = new CommandContext();

		RuntimeException ex = assertThrows(RuntimeException.class, () ->
				FunctionMethods.truncDate(ctx, "DAY")
		);

		assertTrue(ex.getMessage().contains(SourceSystemFunctions.DATE_TRUNC));
	}

	@Test
	public void testTruncDateInvalidDateType() {
		CommandContext ctx = new CommandContext();

		RuntimeException ex = assertThrows(RuntimeException.class, () ->
				FunctionMethods.truncDate(ctx, "DAY", 12345)
		);

		assertTrue(ex.getMessage().contains("This is the message i guess: 'date' in function 'DATE_TRUNC'"));
	}

	@Test
	void similarity() throws FunctionExecutionException {
        //noinspection DataFlowIssue
        similarityThrowCheck(() -> FunctionMethods.similarity(null, null));
		//noinspection DataFlowIssue
        similarityThrowCheck(() -> FunctionMethods.similarity(null, ""));
		//noinspection DataFlowIssue
        similarityThrowCheck(() -> FunctionMethods.similarity("", null));

		assertThat(FunctionMethods.similarity("", "", "levenshtein"))
				.isEqualTo(1.0);
		assertThat(FunctionMethods.similarity("", "", "jarowinkler"))
				.isEqualTo(1.0);
		assertThatThrownBy(() -> FunctionMethods.similarity("", "", "cosine"))
				.isInstanceOf(IllegalArgumentException.class)
				.hasMessage("Invalid text");

		final String v1 = "New York";
		final String v2 = "New Hampshire";
		assertThat(FunctionMethods.similarity(v1, v2, "cosine"))
				.isGreaterThan(.3);
		assertThat(FunctionMethods.similarity(v1, v2, "levenshtein"))
				.isGreaterThan(.3);
		assertThat(FunctionMethods.similarity(v1, v2, "jarowinkler"))
				.isGreaterThan(.3);

		// default is "levenshtein"
		assertThat(FunctionMethods.similarity(v1, v2)).
				isEqualTo(FunctionMethods.similarity(v1, v2, "levenshtein"));

		similarityCheck("cosine", .7, .7, 0);
		similarityCheck("COSINE", .7, .7, 0);
		similarityCheck("COsiNE", .7, .7, 0);
		similarityCheck("levenshtein", .375, .23, 0);
		similarityCheck("jarowinkler", .85, .82, .47);
	}


	private static void similarityCheck(String algorithm, double v1, double v2, double v3) throws FunctionExecutionException {
		assertThat(FunctionMethods.similarity("San Jose", "San", algorithm)).isCloseTo(v1, within(0.1));
		assertThat(FunctionMethods.similarity("San Francisco", "San", algorithm)).isCloseTo(v2, within(0.1));
		assertThat(FunctionMethods.similarity("NY", "San", algorithm)).isCloseTo(0, within(0.1));
		assertThat(FunctionMethods.similarity("Birmingham", "San", algorithm)).isCloseTo(v3, within(0.1));
	}

	private static void similarityThrowCheck(ThrowableAssert.ThrowingCallable throwingCallable) {
		assertThatThrownBy(throwingCallable)
				.isInstanceOf(FunctionExecutionException.class)
				.hasMessage("DVCORE8780 Passed values must not be null");
	}
}
