/* SPDX-FileCopyrightText: 2023 Blender Authors
 *
 * SPDX-License-Identifier: GPL-2.0-or-later */

#include "DNA_mesh_types.h"

#include "node_geometry_util.hh"

namespace blender::nodes::node_geo_input_mesh_edge_vertices_cc {

static void node_declare(NodeDeclarationBuilder &b)
{
  b.add_output<decl::Int>("Vertex Index 1"_ustr)
      .structure_type(StructureType::Field)
      .description("The index of the first vertex in the edge");
  b.add_output<decl::Int>("Vertex Index 2"_ustr)
      .structure_type(StructureType::Field)
      .description("The index of the second vertex in the edge");
  b.add_output<decl::Vector>("Position 1"_ustr)
      .structure_type(StructureType::Field)
      .description("The position of the first vertex in the edge");
  b.add_output<decl::Vector>("Position 2"_ustr)
      .structure_type(StructureType::Field)
      .description("The position of the second vertex in the edge");
}

enum class VertNumber { V1, V2 };

static VArray<int> construct_edge_verts_gvarray(const Mesh &mesh,
                                                const VertNumber vertex,
                                                const AttrDomain domain)
{
  const Span<int2> edges = mesh.edges();
  if (domain == AttrDomain::Edge) {
    if (vertex == VertNumber::V1) {
      return VArray<int>::from_func(edges.size(), [edges](const int i) { return edges[i][0]; });
    }
    return VArray<int>::from_func(edges.size(), [edges](const int i) { return edges[i][1]; });
  }
  return {};
}

class EdgeVertsInput final : public bke::MeshFieldInput {
 private:
  VertNumber vertex_;

 public:
  EdgeVertsInput(VertNumber vertex)
      : bke::MeshFieldInput(CPPType::get<int>(), "Edge Vertices Field"), vertex_(vertex)
  {
  }

  GVArray get_varray_for_context(const Mesh &mesh,
                                 const AttrDomain domain,
                                 const IndexMask & /*mask*/) const final
  {
    return construct_edge_verts_gvarray(mesh, vertex_, domain);
  }

  void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep & /*deep_hash_cache*/) const override
  {
    static constexpr int8_t id = 0;
    hash.add(&id);
    hash.add(vertex_);
  }

  std::optional<AttrDomain> preferred_domain(const Mesh & /*mesh*/) const override
  {
    return AttrDomain::Edge;
  }
};

static VArray<float3> construct_edge_positions_gvarray(const Mesh &mesh,
                                                       const VertNumber vertex,
                                                       const AttrDomain domain)
{
  const Span<float3> positions = mesh.vert_positions();
  const Span<int2> edges = mesh.edges();

  if (vertex == VertNumber::V1) {
    return mesh.attributes().adapt_domain<float3>(
        VArray<float3>::from_func(
            edges.size(), [positions, edges](const int i) { return positions[edges[i][0]]; }),
        AttrDomain::Edge,
        domain);
  }
  return mesh.attributes().adapt_domain<float3>(
      VArray<float3>::from_func(
          edges.size(), [positions, edges](const int i) { return positions[edges[i][1]]; }),
      AttrDomain::Edge,
      domain);
}

class EdgePositionFieldInput final : public bke::MeshFieldInput {
 private:
  VertNumber vertex_;

 public:
  EdgePositionFieldInput(VertNumber vertex)
      : bke::MeshFieldInput(CPPType::get<float3>(), "Edge Position Field"), vertex_(vertex)
  {
  }

  GVArray get_varray_for_context(const Mesh &mesh,
                                 const AttrDomain domain,
                                 const IndexMask & /*mask*/) const final
  {
    return construct_edge_positions_gvarray(mesh, vertex_, domain);
  }

  void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep & /*deep_hash_cache*/) const override
  {
    static constexpr int8_t id = 0;
    hash.add(&id);
    hash.add(vertex_);
  }

  std::optional<AttrDomain> preferred_domain(const Mesh & /*mesh*/) const override
  {
    return AttrDomain::Edge;
  }
};

static void node_geo_exec(GeoNodeExecParams params)
{
  params.set_output("Vertex Index 1"_ustr, Field<int>::from_input<EdgeVertsInput>(VertNumber::V1));
  params.set_output("Vertex Index 2"_ustr, Field<int>::from_input<EdgeVertsInput>(VertNumber::V2));
  params.set_output("Position 1"_ustr,
                    Field<float3>::from_input<EdgePositionFieldInput>(VertNumber::V1));
  params.set_output("Position 2"_ustr,
                    Field<float3>::from_input<EdgePositionFieldInput>(VertNumber::V2));
}

static void node_register()
{
  static bke::bNodeType ntype;
  geo_node_type_base(
      &ntype, "GeometryNodeInputMeshEdgeVertices"_ustr, GEO_NODE_INPUT_MESH_EDGE_VERTICES);
  ntype.ui_name = "Edge Vertices";
  ntype.ui_description = "Retrieve topology information relating to each edge of a mesh";
  ntype.enum_name_legacy = "MESH_EDGE_VERTICES";
  ntype.nclass = NODE_CLASS_INPUT;
  ntype.declare = node_declare;
  ntype.geometry_node_execute = node_geo_exec;
  bke::node_register_type(ntype);
}
NOD_REGISTER_NODE(node_register)

}  // namespace blender::nodes::node_geo_input_mesh_edge_vertices_cc
