/*
 * 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.iotdb.db.queryengine.transformation.datastructure;

import org.apache.iotdb.db.queryengine.transformation.datastructure.row.SerializableRowList;

import org.apache.tsfile.block.column.Column;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.read.common.Field;
import org.apache.tsfile.read.common.RowRecord;
import org.apache.tsfile.read.common.block.column.BinaryColumnBuilder;
import org.apache.tsfile.read.common.block.column.BooleanColumnBuilder;
import org.apache.tsfile.read.common.block.column.DoubleColumnBuilder;
import org.apache.tsfile.read.common.block.column.FloatColumnBuilder;
import org.apache.tsfile.read.common.block.column.IntColumnBuilder;
import org.apache.tsfile.read.common.block.column.LongColumnBuilder;
import org.apache.tsfile.read.common.block.column.TimeColumnBuilder;
import org.apache.tsfile.utils.Binary;
import org.apache.tsfile.utils.BytesUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class SerializableRowListTest extends SerializableListTest {

  private static final TSDataType[] DATA_TYPES = {
    TSDataType.INT32,
    TSDataType.INT64,
    TSDataType.FLOAT,
    TSDataType.DOUBLE,
    TSDataType.BOOLEAN,
    TSDataType.TEXT
  };

  private List<RowRecord> originalList;
  private SerializableRowList testList;

  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    originalList = new ArrayList<>();
    testList = SerializableRowList.construct(QUERY_ID, DATA_TYPES);
  }

  @Override
  @After
  public void tearDown() {
    super.tearDown();
  }

  @Test
  public void serializeAndDeserializeTest() {
    for (int i = 0; i < ITERATION_TIMES; ++i) {
      RowRecord row = generateRowRecord(i);
      originalList.add(row);
    }
    Column[] columns = generateColumns();
    testList.putColumns(columns);

    serializeAndDeserializeOnce();
    serializeAndDeserializeOnce();
  }

  protected RowRecord generateRowRecord(int index) {
    RowRecord rowRecord = new RowRecord(index);
    for (TSDataType dataType : DATA_TYPES) {
      switch (dataType) {
        case INT32:
          rowRecord.addField(index, dataType);
          break;
        case INT64:
          rowRecord.addField((long) index, dataType);
          break;
        case FLOAT:
          rowRecord.addField((float) index, dataType);
          break;
        case DOUBLE:
          rowRecord.addField((double) index, dataType);
          break;
        case BOOLEAN:
          rowRecord.addField(index % 2 == 0, dataType);
          break;
        case TEXT:
          rowRecord.addField(BytesUtils.valueOf(String.valueOf(index)), dataType);
          break;
      }
    }

    return rowRecord;
  }

  protected Column[] generateColumns() {
    Column[] columns = new Column[DATA_TYPES.length + 1];

    // Int columns
    IntColumnBuilder intColumnBuilder = new IntColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      intColumnBuilder.writeInt(i);
    }
    columns[0] = intColumnBuilder.build();

    // Long columns
    LongColumnBuilder longColumnBuilder = new LongColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      longColumnBuilder.writeLong(i);
    }
    columns[1] = longColumnBuilder.build();

    // Float columns
    FloatColumnBuilder floatColumnBuilder = new FloatColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      floatColumnBuilder.writeFloat(i);
    }
    columns[2] = floatColumnBuilder.build();

    // Double columns
    DoubleColumnBuilder doubleColumnBuilder = new DoubleColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      doubleColumnBuilder.writeDouble(i);
    }
    columns[3] = doubleColumnBuilder.build();

    // Boolean columns
    BooleanColumnBuilder booleanColumnBuilder = new BooleanColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      booleanColumnBuilder.writeBoolean(i % 2 == 0);
    }
    columns[4] = booleanColumnBuilder.build();

    // Binary columns
    BinaryColumnBuilder binaryColumnBuilder = new BinaryColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      Binary binary = BytesUtils.valueOf(String.valueOf(i));
      binaryColumnBuilder.writeBinary(binary);
    }
    columns[5] = binaryColumnBuilder.build();

    // The last time columns
    TimeColumnBuilder timeColumnBuilder = new TimeColumnBuilder(null, ITERATION_TIMES);
    for (int i = 0; i < ITERATION_TIMES; i++) {
      timeColumnBuilder.writeLong(i);
    }
    columns[6] = timeColumnBuilder.build();

    return columns;
  }

  protected void serializeAndDeserializeOnce() {
    try {
      testList.serialize();
    } catch (IOException e) {
      fail();
    }
    try {
      testList.deserialize();
    } catch (IOException e) {
      fail();
    }
    assertEquals(ITERATION_TIMES, testList.size());

    for (int i = 0; i < testList.size(); ++i) {
      assertEquals(originalList.get(i).getTimestamp(), testList.getTime(i));
      List<Field> originalFields = originalList.get(i).getFields();
      Object[] testFields = testList.getRow(i);
      for (int j = 0; j < DATA_TYPES.length; ++j) {
        switch (DATA_TYPES[j]) {
          case INT32:
            assertEquals(originalFields.get(j).getIntV(), (int) testFields[j]);
            break;
          case INT64:
            assertEquals(originalFields.get(j).getLongV(), (long) testFields[j]);
            break;
          case FLOAT:
            assertEquals(originalFields.get(j).getFloatV(), (float) testFields[j], 0);
            break;
          case DOUBLE:
            assertEquals(originalFields.get(j).getDoubleV(), (double) testFields[j], 0);
            break;
          case BOOLEAN:
            assertEquals(originalFields.get(j).getBoolV(), testFields[j]);
            break;
          case TEXT:
            assertEquals(originalFields.get(j).getBinaryV(), testFields[j]);
            break;
        }
      }
    }
  }
}
