/*
 * Licensed 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 io.trino.plugin.kudu;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.RecordCursor;
import io.trino.spi.type.Type;
import org.apache.kudu.client.KeyEncoderAccessor;
import org.apache.kudu.client.KuduException;
import org.apache.kudu.client.KuduScanner;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.PartialRow;
import org.apache.kudu.client.RowResult;
import org.apache.kudu.client.RowResultIterator;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import static io.trino.plugin.kudu.KuduColumnHandle.ROW_ID_POSITION;
import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static java.util.Objects.requireNonNull;

public class KuduRecordCursor
        implements RecordCursor
{
    private static final Field ROW_DATA_FIELD;

    static {
        try {
            ROW_DATA_FIELD = RowResult.class.getDeclaredField("rowData");
            ROW_DATA_FIELD.setAccessible(true);
        }
        catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    private final KuduScanner scanner;
    private final List<Type> columnTypes;
    private final KuduTable table;
    private final Map<Integer, Integer> fieldMapping;
    private RowResultIterator nextRows;
    private RowResult currentRow;

    private long totalBytes;
    private boolean started;

    public KuduRecordCursor(KuduScanner scanner, KuduTable table, List<Type> columnTypes, Map<Integer, Integer> fieldMapping)
    {
        this.scanner = requireNonNull(scanner, "scanner is null");
        this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null"));
        this.table = requireNonNull(table, "table is null");
        this.fieldMapping = ImmutableMap.copyOf(requireNonNull(fieldMapping, "fieldMapping is null"));
    }

    @Override
    public long getCompletedBytes()
    {
        return totalBytes;
    }

    @Override
    public long getReadTimeNanos()
    {
        return 0;
    }

    @Override
    public Type getType(int field)
    {
        return columnTypes.get(field);
    }

    private int mapping(int field)
    {
        return fieldMapping.get(field);
    }

    /**
     * get next Row/Page
     */
    @Override
    public boolean advanceNextPosition()
    {
        boolean needNextRows = !started || !nextRows.hasNext();

        if (!started) {
            started = true;
        }

        if (needNextRows) {
            currentRow = null;
            try {
                do {
                    if (!scanner.hasMoreRows()) {
                        return false;
                    }

                    nextRows = scanner.nextRows();
                }
                while (!nextRows.hasNext());
            }
            catch (KuduException e) {
                throw new RuntimeException(e);
            }
        }

        currentRow = nextRows.next();
        totalBytes += getRowLength();
        return true;
    }

    private org.apache.kudu.util.Slice getCurrentRowRawData()
    {
        if (currentRow != null) {
            try {
                return (org.apache.kudu.util.Slice) ROW_DATA_FIELD.get(currentRow);
            }
            catch (IllegalAccessException e) {
                throw new TrinoException(GENERIC_INTERNAL_ERROR, e);
            }
        }
        return null;
    }

    private int getRowLength()
    {
        org.apache.kudu.util.Slice rawData = getCurrentRowRawData();
        if (rawData != null) {
            return rawData.length();
        }
        return columnTypes.size();
    }

    @Override
    public boolean getBoolean(int field)
    {
        int index = mapping(field);
        return TypeHelper.getBoolean(columnTypes.get(field), currentRow, index);
    }

    @Override
    public long getLong(int field)
    {
        int index = mapping(field);
        return TypeHelper.getLong(columnTypes.get(field), currentRow, index);
    }

    @Override
    public double getDouble(int field)
    {
        int index = mapping(field);
        return TypeHelper.getDouble(columnTypes.get(field), currentRow, index);
    }

    @Override
    public Slice getSlice(int field)
    {
        int index = mapping(field);
        if (index == ROW_ID_POSITION) {
            PartialRow partialRow = buildPrimaryKey();
            return Slices.wrappedBuffer(KeyEncoderAccessor.encodePrimaryKey(partialRow));
        }
        return TypeHelper.getSlice(columnTypes.get(field), currentRow, index);
    }

    @Override
    public Object getObject(int field)
    {
        int index = mapping(field);
        return TypeHelper.getObject(columnTypes.get(field), currentRow, index);
    }

    @Override
    public boolean isNull(int field)
    {
        int mappedField = mapping(field);
        return mappedField >= 0 && currentRow.isNull(mappedField);
    }

    private PartialRow buildPrimaryKey()
    {
        PartialRow row = new PartialRow(table.getSchema());
        RowHelper.copyPrimaryKey(table.getSchema(), currentRow, row);
        return row;
    }

    @Override
    public void close()
    {
        if (!started) {
            return;
        }
        try {
            scanner.close();
        }
        catch (KuduException e) {
            throw new RuntimeException(e);
        }
        currentRow = null;
        nextRows = null;
    }
}

@@ -993,16 +993,67 @@
 canner;%0A
+import org.apache.kudu.client.KuduScannerIterator;%0A
 import o
@@ -1171,57 +1171,8 @@
 ult;
-%0Aimport org.apache.kudu.client.RowResultIterator;
 %0A%0Aim
@@ -1992,34 +1992,53 @@
 ate 
-RowResultIterator nextRows
+final KuduScannerIterator kuduScannerIterator
 ;%0A  
@@ -2102,37 +2102,8 @@
 tes;
-%0A    private boolean started;
 %0A%0A  
@@ -2560,24 +2560,74 @@
 is null%22));%0A
+        kuduScannerIterator = scanner.iterator();%0A
     %7D%0A%0A    @
@@ -3094,284 +3094,46 @@
     
-boolean needNextRows = !started %7C%7C !nextRows.hasNext();%0A%0A        if (!started) %7B%0A            started = true;%0A        %7D%0A%0A        if (needNextRows) %7B%0A            currentRow = null;%0A            try %7B%0A                do %7B%0A                    if (!scanner.hasMoreRows()) %7B%0A        
+if (!kuduScannerIterator.hasNext()) %7B%0A
     
@@ -3136,28 +3136,24 @@
             
-    
 return false
@@ -3154,28 +3154,16 @@
  false;%0A
-            
         
@@ -3177,267 +3177,40 @@
     
- 
-           nextRows = scanner.nextRows();%0A                %7D%0A                while (!nextRows.hasNext());%0A            %7D%0A            catch (KuduException e) %7B%0A                throw new RuntimeException(e);%0A            %7D%0A        %7D%0A%0A        currentRow = nextRows
+currentRow = kuduScannerIterator
 .nex
@@ -5416,62 +5416,8 @@
   %7B%0A
-        if (!started) %7B%0A            return;%0A        %7D%0A
     
@@ -5583,33 +5583,8 @@
 ll;%0A
-        nextRows = null;%0A
     

Use KuduScannerIterator instead of RowResultIterator