package com.capgemini.reports.database.manager;

import com.capgemini.framework.common.DateHelper;
import com.capgemini.reports.database.javabean.DbReport;
import com.capgemini.reports.database.javabean.DbReportOwner;
import com.capgemini.reports.database.javabean.DbUser;
import com.capgemini.reports.database.manager.MngReport.RunningReportEntry;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Query;
import org.hibernate.Session;

import java.util.List;

/**
 * Hibernate manager for DBReport JAVA bean.
 **/
@Slf4j
public class MngReportOwner extends AbstractHibernateManager<DbReportOwner> {

  private static final String SELECT_REPORT_OWNERS;

  static {
    SELECT_REPORT_OWNERS = "from DbReportOwner where reportId = :DbReportId order by id desc";
  }

  @Override
  public Class<DbReportOwner> getManagedClass() {
    return DbReportOwner.class;
  }

  /**
   * Create a new affectation of a report execution to a user in database.
   */
  protected DbReportOwner insert(Session session, final DbReport aReport, final DbUser aUser) {
    log.debug("Inserting DbReportOwner entry report={}({}) - owner={}({})", aReport.getId(), aReport.getReportCode(), aUser.getId(), aUser.getLogin());
    DbReportOwner theReportOwner = new DbReportOwner();

    // Assign default attribute values
    theReportOwner.setReportId(aReport.getId());
    theReportOwner.setUserId(aUser.getId());
    theReportOwner.setRequestDate(DateHelper.getCurrentSqlTimestamp());

    // Persist object
    session.save(theReportOwner);
    return theReportOwner;
  }

  /**
   * Search for all the {@link DbReportOwner}s that subscribed to the report whose ID is provided. A result page number above 0 can be provided to browse further results.
   */
  public List<DbReportOwner> searchReportOwners(Session session, final Long aReportId) {
    Query theQuery = session.createQuery(SELECT_REPORT_OWNERS);
    theQuery.setLong("DbReportId", aReportId);
    return castAll(theQuery.list());
  }

  /**
   * Creates and persists a {@link DbReportOwner} instance linking the provided {@link DbUser} to the provided report.
   */
  public void subscribe(Session session, final DbUser dbUser, final RunningReportEntry report) {
    insert(session, report.getReport(), dbUser);
  }
}
