/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.directory.server.core.partition.impl.btree.jdbm;


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

import java.io.File;

import jdbm.RecordManager;
import jdbm.helper.DefaultSerializer;
import jdbm.recman.BaseRecordManager;

import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.Cursor;
import org.apache.directory.api.ldap.model.cursor.InvalidCursorPositionException;
import org.apache.directory.api.ldap.model.cursor.Tuple;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.api.ldap.model.schema.comparators.SerializableComparator;
import org.apache.directory.api.ldap.schema.extractor.SchemaLdifExtractor;
import org.apache.directory.api.ldap.schema.extractor.impl.DefaultSchemaLdifExtractor;
import org.apache.directory.api.ldap.schema.loader.LdifSchemaLoader;
import org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager;
import org.apache.directory.api.util.exception.Exceptions;
import org.apache.directory.server.core.api.partition.PartitionTxn;
import org.apache.directory.server.xdbm.MockPartitionReadTxn;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Tests the DupsContainerCursor.
 *
 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
 */
@Execution(ExecutionMode.SAME_THREAD)
public class DupsContainerCursorTest
{
    private static final Logger LOG = LoggerFactory.getLogger( NoDupsCursorTest.class );
    private static final String TEST_OUTPUT_PATH = "test.output.path";

    JdbmTable<String, String> table;
    File dbFile;
    private static SchemaManager schemaManager;
    RecordManager recman;
    private static final int SIZE = 15;
    private PartitionTxn partitionTxn;


    @BeforeAll
    public static void init() throws Exception
    {
        String workingDirectory = System.getProperty( "workingDirectory" );

        if ( workingDirectory == null )
        {
            String path = DupsContainerCursorTest.class.getResource( "" ).getPath();
            int targetPos = path.indexOf( "target" );
            workingDirectory = path.substring( 0, targetPos + 6 );
        }

        File schemaRepository = new File( workingDirectory, "schema" );
        SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( new File( workingDirectory ) );
        extractor.extractOrCopy( true );
        LdifSchemaLoader loader = new LdifSchemaLoader( schemaRepository );
        schemaManager = new DefaultSchemaManager( loader );

        boolean loaded = schemaManager.loadAllEnabled();

        if ( !loaded )
        {
            fail( "Schema load failed : " + Exceptions.printErrors( schemaManager.getErrors() ) );
        }
    }


    @BeforeEach
    public void createTable() throws Exception
    {
        File tmpDir = null;

        if ( System.getProperty( TEST_OUTPUT_PATH, null ) != null )
        {
            tmpDir = new File( System.getProperty( TEST_OUTPUT_PATH ) );
            tmpDir.deleteOnExit();
        }

        dbFile = File.createTempFile( getClass().getSimpleName(), "db", tmpDir );
        dbFile.deleteOnExit();
        recman = new BaseRecordManager( dbFile.getAbsolutePath() );

        SerializableComparator<String> comparator = new SerializableComparator<String>(
            SchemaConstants.INTEGER_ORDERING_MATCH_MR_OID );
        comparator.setSchemaManager( schemaManager );
        table = new JdbmTable<String, String>( schemaManager, "test", SIZE, recman,
            comparator, comparator, null, new DefaultSerializer() );
        partitionTxn = new MockPartitionReadTxn();
        LOG.debug( "Created new table and populated it with data" );
    }


    @AfterEach
    public void destroyTable() throws Exception
    {
        table.close( partitionTxn );
        table = null;
        recman.close();
        recman = null;
        String fileToDelete = dbFile.getAbsolutePath();
        new File( fileToDelete ).delete();
        new File( fileToDelete + ".db" ).delete();
        new File( fileToDelete + ".lg" ).delete();
        dbFile = null;
    }


    @Test
    public void testUsingNoDuplicates() throws Exception
    {
        assertThrows( IllegalStateException.class, () ->
        {
            recman = new BaseRecordManager( dbFile.getAbsolutePath() );
    
            // gosh this is a terrible use of a global static variable
            //SerializableComparator.setRegistry(
            //    new MockComparatorRegistry(
            //        new OidRegistry() ) );
            SerializableComparator<String> comparator = new SerializableComparator<String>(
                SchemaConstants.INTEGER_ORDERING_MATCH_MR_OID );
            comparator.setSchemaManager( schemaManager );
            table = new JdbmTable<String, String>( schemaManager, "test", recman, comparator, null, null );
    
            try ( Cursor<Tuple<String, DupsContainer<String>>> cursor = 
                new DupsContainerCursor<String, String>( table ) )
            {
            }
        } );
    }


    @Test
    public void testEmptyTable() throws Exception
    {
        Cursor<Tuple<String, DupsContainer<String>>> cursor =
            new DupsContainerCursor<String, String>( table );
        assertNotNull( cursor );

        assertFalse( cursor.available() );
        assertFalse( cursor.isClosed() );
        cursor.close();

        cursor = new DupsContainerCursor<String, String>( table );
        assertFalse( cursor.previous() );
        cursor.close();

        cursor = new DupsContainerCursor<String, String>( table );
        assertFalse( cursor.next() );

        cursor.after( new Tuple<String, DupsContainer<String>>( "7", null ) );

        try
        {
            cursor.get();
            fail();
        }
        catch ( InvalidCursorPositionException icpe )
        {
            // Expected
            cursor.close();
        }
    }


    @Test
    public void testOnTableWithSingleEntry() throws Exception
    {
        table.put( partitionTxn, "1", "1" );
        Cursor<Tuple<String, DupsContainer<String>>> cursor =
            new DupsContainerCursor<String, String>( table );
        assertTrue( cursor.first() );

        Tuple<String, DupsContainer<String>> tuple = cursor.get();
        assertEquals( "1", tuple.getKey() );
        assertEquals( "1", tuple.getValue().getArrayTree().getFirst() );

        cursor.beforeFirst();
        assertFalse( cursor.previous() );
        assertTrue( cursor.next() );
        cursor.close();
    }


    @Test
    public void testOnTableWithMultipleEntries() throws Exception
    {
        for ( int i = 1; i < 10; i++ )
        {
            String istr = Integer.toString( i );
            table.put( partitionTxn, istr, istr );
        }

        Cursor<Tuple<String, DupsContainer<String>>> cursor =
            new DupsContainerCursor<String, String>( table );

        cursor.after( new Tuple<String, DupsContainer<String>>( "2", null ) );
        assertTrue( cursor.next() );

        Tuple<String, DupsContainer<String>> tuple = cursor.get();
        assertEquals( "3", tuple.getKey() );
        assertEquals( "3", tuple.getValue().getArrayTree().getFirst() );

        cursor.before( new Tuple<String, DupsContainer<String>>( "7", null ) );
        cursor.next();
        tuple = cursor.get();
        assertEquals( "7", tuple.getKey() );
        assertEquals( "7", tuple.getValue().getArrayTree().getFirst() );

        cursor.last();
        cursor.next();
        assertFalse( cursor.available() );
        /* tuple = cursor.get();
         assertTrue( tuple.getKey().equals( 9 ) );
         assertEquals( 9, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); */

        cursor.beforeFirst();
        cursor.next();
        tuple = cursor.get();
        assertEquals( "1", tuple.getKey() );
        assertEquals( "1", tuple.getValue().getArrayTree().getFirst() );

        cursor.afterLast();
        assertFalse( cursor.next() );

        cursor.beforeFirst();
        assertFalse( cursor.previous() );

        // just to clear the jdbmTuple value so that line 127 inside after(tuple) method
        // can be executed as part of the below after(tuple) call
        cursor.before( new Tuple<String, DupsContainer<String>>( "1", null ) );
        cursor.after( new Tuple<String, DupsContainer<String>>( "0", null ) ); // this positions on tuple with key 1

        cursor.next(); // this moves onto tuple with key 2
        tuple = cursor.get();
        assertEquals( "2", tuple.getKey() );
        assertEquals( "2", tuple.getValue().getArrayTree().getFirst() );
        cursor.close();
    }


    @Test
    public void testMiscellaneous() throws Exception
    {
    }
}