/*
  Copyright (c) 2003-2025 YourKit GmbH
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

  * Neither the name of YourKit nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY YOURKIT "AS IS" AND ANY
  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL YOURKIT BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.yourkit.probes.builtin;

import com.yourkit.asserts.NotNull;
import com.yourkit.asserts.Nullable;
import com.yourkit.probes.*;

import static com.yourkit.probes.ReflectionUtil.callMethod0;

public class JPA_Hibernate {
  private static final class RequestTable extends Table {
    private final StringColumn myMethod = new StringColumn("Method");
    private final StringColumn myDetail = new StringColumn("Detail");

    public RequestTable(@NotNull final String name) {
      super(JPA_Hibernate.class, name, Table.MASK_FOR_LASTING_EVENTS);
    }
  }
  private static final RequestTable TABLE = new RequestTable(JPA_HibernateConstants.TABLE_NAME);

  @Nullable
  private static String getQueryDetail(@NotNull final Object query) {
    // Hibernate 5.2
    final String queryString = (String)callMethod0(query, "getQueryString");
    if (queryString != null) {
      return queryString;
    }

    // Hibernate 5.1
    // getHibernateQuery().getQueryString()
    final Object hibernateQuery = callMethod0(query, "getHibernateQuery");
    if (hibernateQuery != null) {
      return (String)callMethod0(hibernateQuery, "getQueryString");
    }

    return null;
  }

  // query

  @MethodPattern({
    "org.hibernate.*Query*:getResultList() java.util.List",
    "org.hibernate.*Query*:getSingleResult() Object",
    "org.hibernate.*Query*:executeUpdate() int"
  })
  public static final class Query {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @This final Object query,
      @MethodName final String methodName,
      @ThrownException final Throwable exception
    ) {
      if (Table.shouldIgnoreRow(row)) {
        // optimization
        return;
      }

      final String detail = getQueryDetail(query);

      exit(row, methodName, detail, exception);
    }
  }

  // Entity manager methods

  @MethodPattern({
    "org.hibernate.internal.SessionImpl : persist(Object) void",
    "org.hibernate.internal.SessionImpl : close()",
    // Hibernate 5.2
    "org.hibernate.internal.SessionImpl : find(Class, Object, jakarta.persistence.LockModeType, java.util.Map)",
    "org.hibernate.internal.SessionImpl : find(Class, Object, javax.persistence.LockModeType, java.util.Map)",
    // Hibernate 5.1
    "org.hibernate.jpa.spi.AbstractEntityManagerImpl : find(Class, Object, jakarta.persistence.LockModeType, java.util.Map)",
    "org.hibernate.jpa.spi.AbstractEntityManagerImpl : find(Class, Object, javax.persistence.LockModeType, java.util.Map)"
  })
  public static final class EMMethod {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @Param(1) final Object entityOrClass,
      @MethodName final String methodName,
      @ThrownException final Throwable exception
    ) {
      if (Table.shouldIgnoreRow(row)) {
        // optimization
        return;
      }

      exit(
        row,
        methodName,
        entityOrClass != null ? (entityOrClass instanceof Class ? (Class<?>)entityOrClass : entityOrClass.getClass()).getName() : null,
        exception
      );
    }
  }

  // other operations

  @MethodPattern({
    "org.hibernate.collection.internal.AbstractPersistentCollection : read()",
    "org.hibernate.collection.internal.AbstractPersistentCollection : write()",
    // Hibernate 6.0
    "org.hibernate.collection.spi.AbstractPersistentCollection : read()",
    "org.hibernate.collection.spi.AbstractPersistentCollection : write()"
  })
  public static final class other {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @MethodName final String methodName,
      @ThrownException final Throwable exception
    ) {
      exit(row, methodName, null, exception);
    }
  }

  // transactions

  @MethodPattern({
    "org.hibernate.engine.transaction.internal.TransactionImpl : begin() void",
    "org.hibernate.engine.transaction.internal.TransactionImpl : commit() void"
  })
  public static final class Commit {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @MethodName final String methodName,
      @ThrownException final Throwable exception
    ) {
      exit(row, methodName, null, exception);
    }
  }

  // create entity manager factory (EMF)

  @MethodPattern("org.hibernate.jpa.HibernatePersistenceProvider : createEntityManagerFactory(String, java.util.Map)")
  public static final class createEMF {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @ReturnValue @Nullable final Object createdFactory,
      @Param(1) final String name,
      @ThrownException final Throwable exception
    ) {
      if (Table.shouldIgnoreRow(row)) {
        // optimization
        return;
      }

      exit(
        row,
        "createEntityManagerFactory",
        name + (createdFactory != null ? "" : " (result: null)"),
        exception
      );
    }
  }

  // close entity manager factory (EMF)

  @MethodPattern("org.hibernate.internal.SessionFactoryImpl : close()")
  public static final class closeEMF {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @ThrownException final Throwable exception
    ) {
      exit(row, "EntityManagerFactory.close", null, exception);
    }
  }

  // create entity manager (EM)

  @MethodPattern({
    // Hibernate 5.4
    "org.hibernate.internal.SessionFactoryImpl : buildEntityManager(jakarta.persistence.SynchronizationType, java.util.Map)",
    "org.hibernate.internal.SessionFactoryImpl : buildEntityManager(javax.persistence.SynchronizationType, java.util.Map)",
    // Hibernate 5.1
    "org.hibernate.jpa.internal.EntityManagerFactoryImpl : internalCreateEntityManager(jakarta.persistence.SynchronizationType, java.util.Map)",
    "org.hibernate.jpa.internal.EntityManagerFactoryImpl : internalCreateEntityManager(javax.persistence.SynchronizationType, java.util.Map)"
  })
  public static final class CreateEM {
    public static int onEnter() {
      return enter();
    }

    public static void onExit(
      @OnEnterResult final int row,
      @ReturnValue @Nullable final Object createdFactory,
      @ThrownException final Throwable exception
    ) {
      exit(
        row,
        "createEntityManager",
        createdFactory == null ? "result: null" : null,
        exception
      );
    }
  }

  // common methods

  static int enter() {
    return TABLE.createRow();
  }

  static void exit(
    @OnEnterResult final int row,
    @MethodName final String methodName,
    @Nullable final String detail,
    @Nullable final Throwable exception
  ) {
    TABLE.closeRow(row, exception);
    TABLE.myMethod.setValue(row, methodName);
    TABLE.myDetail.setValue(row, detail);
  }
}
