/*
 * 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.plan.relational.analyzer;

import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
import org.apache.iotdb.db.queryengine.plan.relational.metadata.QualifiedObjectName;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.QualifiedName;

import org.apache.tsfile.read.common.type.Type;

import java.util.Optional;

import static java.util.Objects.requireNonNull;

public class Field {
  private final Optional<QualifiedObjectName> originTable;
  private final Optional<String> originColumnName;
  private final Optional<QualifiedName> relationAlias;
  private final Optional<String> name;
  private final Type type;

  private final TsTableColumnCategory columnCategory;

  private final boolean hidden;
  private final boolean aliased;

  public static Field newUnqualified(String name, Type type, TsTableColumnCategory columnCategory) {
    requireNonNull(name, "name is null");
    requireNonNull(type, "type is null");

    return new Field(
        Optional.empty(),
        Optional.of(name),
        type,
        columnCategory,
        false,
        Optional.empty(),
        Optional.empty(),
        false);
  }

  public static Field newUnqualified(
      Optional<String> name, Type type, TsTableColumnCategory columnCategory) {
    requireNonNull(name, "name is null");
    requireNonNull(type, "type is null");

    return new Field(
        Optional.empty(),
        name,
        type,
        columnCategory,
        false,
        Optional.empty(),
        Optional.empty(),
        false);
  }

  public static Field newUnqualified(
      Optional<String> name,
      Type type,
      TsTableColumnCategory columnCategory,
      Optional<QualifiedObjectName> originTable,
      Optional<String> originColumn,
      boolean aliased) {
    requireNonNull(name, "name is null");
    requireNonNull(type, "type is null");
    requireNonNull(originTable, "originTable is null");

    return new Field(
        Optional.empty(), name, type, columnCategory, false, originTable, originColumn, aliased);
  }

  public static Field newQualified(
      QualifiedName relationAlias,
      Optional<String> name,
      Type type,
      TsTableColumnCategory columnCategory,
      boolean hidden,
      Optional<QualifiedObjectName> originTable,
      Optional<String> originColumn,
      boolean aliased) {
    requireNonNull(relationAlias, "relationAlias is null");
    requireNonNull(name, "name is null");
    requireNonNull(type, "type is null");
    requireNonNull(originTable, "originTable is null");

    return new Field(
        Optional.of(relationAlias),
        name,
        type,
        columnCategory,
        hidden,
        originTable,
        originColumn,
        aliased);
  }

  public Field(
      Optional<QualifiedName> relationAlias,
      Optional<String> name,
      Type type,
      TsTableColumnCategory columnCategory,
      boolean hidden,
      Optional<QualifiedObjectName> originTable,
      Optional<String> originColumnName,
      boolean aliased) {
    requireNonNull(relationAlias, "relationAlias is null");
    requireNonNull(name, "name is null");
    requireNonNull(type, "type is null");
    requireNonNull(originTable, "originTable is null");
    requireNonNull(originColumnName, "originColumnName is null");

    this.relationAlias = relationAlias;
    this.name = name;
    this.type = type;
    this.columnCategory = columnCategory;
    this.hidden = hidden;
    this.originTable = originTable;
    this.originColumnName = originColumnName;
    this.aliased = aliased;
  }

  public Optional<QualifiedObjectName> getOriginTable() {
    return originTable;
  }

  public Optional<String> getOriginColumnName() {
    return originColumnName;
  }

  public Optional<QualifiedName> getRelationAlias() {
    return relationAlias;
  }

  public Optional<String> getName() {
    return name;
  }

  public Type getType() {
    return type;
  }

  public TsTableColumnCategory getColumnCategory() {
    return columnCategory;
  }

  public boolean isHidden() {
    return hidden;
  }

  public boolean isAliased() {
    return aliased;
  }

  public boolean matchesPrefix(Optional<QualifiedName> prefix) {
    return !prefix.isPresent()
        || relationAlias.isPresent() && relationAlias.get().hasSuffix(prefix.get());
  }

  /*
   Namespaces can have names such as "x", "x.y" or "" if there's no name
   Name to resolve can have names like "a", "x.a", "x.y.a"

   namespace  name     possible match
    ""         "a"           y
    "x"        "a"           y
    "x.y"      "a"           y

    ""         "x.a"         n
    "x"        "x.a"         y
    "x.y"      "x.a"         n

    ""         "x.y.a"       n
    "x"        "x.y.a"       n
    "x.y"      "x.y.a"       n

    ""         "y.a"         n
    "x"        "y.a"         n
    "x.y"      "y.a"         y
  */
  public boolean canResolve(QualifiedName name) {
    if (!this.name.isPresent()) {
      return false;
    }

    // TODO: need to know whether the qualified name and the name of this field were quoted
    return matchesPrefix(name.getPrefix()) && this.name.get().equalsIgnoreCase(name.getSuffix());
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder();
    if (relationAlias.isPresent()) {
      result.append(relationAlias.get()).append(".");
    }

    result.append(name.orElse("<anonymous>")).append(":").append(type);

    return result.toString();
  }
}
