/*
 * Copyright (c) 2011-2022 Contributors to the Eclipse Foundation
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
 * which is available at https://www.apache.org/licenses/LICENSE-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
 */
package io.vertx.jdbcclient.impl;

import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.impl.ArrayTuple;
import io.vertx.sqlclient.impl.RowDesc;

import java.util.List;
import java.util.Objects;

public class JDBCRow extends ArrayTuple implements Row {

  private final RowDesc desc;

  public JDBCRow(RowDesc desc) {
    super(desc.columnNames().size());
    this.desc = desc;
  }

  @Override
  public String getColumnName(int pos) {
    List<String> columnNames = desc.columnNames();
    return pos < 0 || columnNames.size() - 1 < pos ? null : columnNames.get(pos);
  }

  @Override
  public int getColumnIndex(String name) {
    Objects.requireNonNull(name, "'name' cannot be null");
    return desc.columnNames().indexOf(name);
  }

  @Override
  public <T> T get(Class<T> type, int pos) {
    if (type.isEnum()) {
      return type.cast(getEnum(type, pos));
    } else {
      return super.get(type, pos);
    }
  }

  @SuppressWarnings({"rawtypes", "unchecked"})
  private Object getEnum(Class enumType, int position) {
    Object val = getValue(position);
    if (val != null) {
      // val instanceof enumType
      if (val.getClass().isAssignableFrom(enumType)) {
        return enumType.cast(val);
      }

      if (val instanceof String) {
        return Enum.valueOf(enumType, (String) val);
      }

      if (val instanceof Number) {
        int ordinal = ((Number) val).intValue();
        if (ordinal >= 0) {
          Object[] constants = enumType.getEnumConstants();
          if (ordinal < constants.length) {
            return constants[ordinal];
          }
        }
      }
    }
    return null;
  }
}
