package com.ustadmobile.core.db.dao;

import androidx.room.CoroutinesRoom;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.SharedSQLiteStatement;
import androidx.room.util.StringUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.ustadmobile.lib.db.entities.ClazzAssignmentRollUp;
import java.lang.Class;
import java.lang.Exception;
import java.lang.Long;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.lang.SuppressWarnings;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import kotlin.Unit;
import kotlin.coroutines.Continuation;

@SuppressWarnings({"unchecked", "deprecation"})
public final class ClazzAssignmentRollUpDao_Impl extends ClazzAssignmentRollUpDao {
  private final RoomDatabase __db;

  private final EntityInsertionAdapter<ClazzAssignmentRollUp> __insertionAdapterOfClazzAssignmentRollUp;

  private final EntityDeletionOrUpdateAdapter<ClazzAssignmentRollUp> __updateAdapterOfClazzAssignmentRollUp;

  private final SharedSQLiteStatement __preparedStmtOfCacheBestStatements;

  private final SharedSQLiteStatement __preparedStmtOfDeleteCachedInactiveContent;

  private final SharedSQLiteStatement __preparedStmtOfInvalidateCacheByAssignment;

  public ClazzAssignmentRollUpDao_Impl(RoomDatabase __db) {
    this.__db = __db;
    this.__insertionAdapterOfClazzAssignmentRollUp = new EntityInsertionAdapter<ClazzAssignmentRollUp>(__db) {
      @Override
      public String createQuery() {
        return "INSERT OR ABORT INTO `ClazzAssignmentRollUp` (`cacheUid`,`cachePersonUid`,`cacheContentEntryUid`,`cacheClazzAssignmentUid`,`cacheStudentScore`,`cacheMaxScore`,`cacheFinalWeightScoreWithPenalty`,`cacheWeight`,`cacheProgress`,`cacheContentComplete`,`cacheSuccess`,`cachePenalty`,`lastCsnChecked`) VALUES (nullif(?, 0),?,?,?,?,?,?,?,?,?,?,?,?)";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, ClazzAssignmentRollUp value) {
        stmt.bindLong(1, value.getCacheUid());
        stmt.bindLong(2, value.getCachePersonUid());
        stmt.bindLong(3, value.getCacheContentEntryUid());
        stmt.bindLong(4, value.getCacheClazzAssignmentUid());
        stmt.bindLong(5, value.getCacheStudentScore());
        stmt.bindLong(6, value.getCacheMaxScore());
        stmt.bindDouble(7, value.getCacheFinalWeightScoreWithPenalty());
        stmt.bindLong(8, value.getCacheWeight());
        stmt.bindLong(9, value.getCacheProgress());
        final int _tmp = value.getCacheContentComplete() ? 1 : 0;
        stmt.bindLong(10, _tmp);
        stmt.bindLong(11, value.getCacheSuccess());
        stmt.bindLong(12, value.getCachePenalty());
        stmt.bindLong(13, value.getLastCsnChecked());
      }
    };
    this.__updateAdapterOfClazzAssignmentRollUp = new EntityDeletionOrUpdateAdapter<ClazzAssignmentRollUp>(__db) {
      @Override
      public String createQuery() {
        return "UPDATE OR ABORT `ClazzAssignmentRollUp` SET `cacheUid` = ?,`cachePersonUid` = ?,`cacheContentEntryUid` = ?,`cacheClazzAssignmentUid` = ?,`cacheStudentScore` = ?,`cacheMaxScore` = ?,`cacheFinalWeightScoreWithPenalty` = ?,`cacheWeight` = ?,`cacheProgress` = ?,`cacheContentComplete` = ?,`cacheSuccess` = ?,`cachePenalty` = ?,`lastCsnChecked` = ? WHERE `cacheUid` = ?";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, ClazzAssignmentRollUp value) {
        stmt.bindLong(1, value.getCacheUid());
        stmt.bindLong(2, value.getCachePersonUid());
        stmt.bindLong(3, value.getCacheContentEntryUid());
        stmt.bindLong(4, value.getCacheClazzAssignmentUid());
        stmt.bindLong(5, value.getCacheStudentScore());
        stmt.bindLong(6, value.getCacheMaxScore());
        stmt.bindDouble(7, value.getCacheFinalWeightScoreWithPenalty());
        stmt.bindLong(8, value.getCacheWeight());
        stmt.bindLong(9, value.getCacheProgress());
        final int _tmp = value.getCacheContentComplete() ? 1 : 0;
        stmt.bindLong(10, _tmp);
        stmt.bindLong(11, value.getCacheSuccess());
        stmt.bindLong(12, value.getCachePenalty());
        stmt.bindLong(13, value.getLastCsnChecked());
        stmt.bindLong(14, value.getCacheUid());
      }
    };
    this.__preparedStmtOfCacheBestStatements = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = " \n"
                + "        REPLACE INTO ClazzAssignmentRollUp \n"
                + "                (cachePersonUid, cacheContentEntryUid, cacheClazzAssignmentUid, \n"
                + "                 cacheStudentScore, cacheMaxScore, cacheWeight,  cacheProgress,\n"
                + "                 cacheContentComplete, cacheSuccess,cachePenalty, cacheFinalWeightScoreWithPenalty, lastCsnChecked)\n"
                + "                 \n"
                + "        WITH MaxScoreTable (maxScore, maxScoreContentEntryUid) \n"
                + "                AS (SELECT MAX(resultScoreMax), statementContentEntryUid \n"
                + "                      FROM StatementEntity\n"
                + "                     WHERE contentEntryRoot \n"
                + "                  GROUP BY statementContentEntryUid)               \n"
                + "\n"
                + "       SELECT clazzEnrolmentPersonUid AS cachePersonUid, \n"
                + "                COALESCE(cacjContentUid,0) AS cacheContentEntryUid, caUid AS cacheClazzAssignmentUid, \n"
                + "               COALESCE(resultScoreRaw,0) AS cacheStudentScore, \n"
                + "              \n"
                + "              \n"
                + "               COALESCE((SELECT maxScore \n"
                + "                          FROM MaxScoreTable \n"
                + "                         WHERE cacjContentUid = maxScoreContentEntryUid), 0) AS cacheMaxScore,\n"
                + "                         \n"
                + "               COALESCE(cacjWeight, 0) AS cacheWeight,\n"
                + "                        \n"
                + "                          \n"
                + "               COALESCE(StatementEntity.extensionProgress,0) AS cacheProgress,\n"
                + "               COALESCE(StatementEntity.resultCompletion,'FALSE') AS cacheContentComplete, \n"
                + "               COALESCE(StatementEntity.resultSuccess,0) AS cacheSuccess,\n"
                + "               (CASE WHEN StatementEntity.timestamp > CourseBlock.cbDeadlineDate\n"
                + "                     THEN CourseBlock.cbLateSubmissionPenalty \n"
                + "                     ELSE 0 END) AS cachePenalty,\n"
                + "                     \n"
                + "              (CASE WHEN StatementEntity.timestamp > CourseBlock.cbDeadlineDate \n"
                + "                     THEN (COALESCE(CAST(resultScoreRaw AS REAL),0) / COALESCE((SELECT maxScore \n"
                + "                          FROM MaxScoreTable WHERE cacjContentUid = maxScoreContentEntryUid),0) * 100 * cacjWeight * (1 - (CAST(cbLateSubmissionPenalty AS REAL)/100)))\n"
                + "                     ELSE (COALESCE(CAST(resultScoreRaw AS REAL),0) / COALESCE((SELECT maxScore \n"
                + "                          FROM MaxScoreTable WHERE cacjContentUid = maxScoreContentEntryUid),0) * 100 * cacjWeight)  END) AS cacheFinalWeightScoreWithPenalty,   \n"
                + "                     \n"
                + "               0 AS lastCsnChecked\n"
                + "          FROM ClazzAssignmentContentJoin\n"
                + "\t            JOIN ClazzAssignment \n"
                + "                ON ClazzAssignment.caUid = ClazzAssignmentContentJoin.cacjAssignmentUid\n"
                + "                                \n"
                + "                JOIN ClazzEnrolment\n"
                + "                ON ClazzEnrolment.clazzEnrolmentClazzUid = ClazzAssignment.caClazzUid\n"
                + "                \n"
                + "                JOIN CourseBlock\n"
                + "                ON CourseBlock.cbEntityUid = ClazzAssignment.caUid\n"
                + "               AND CourseBlock.cbType = 103 \n"
                + "\t\t\t\t\t      \t      \n"
                + "\t\t\t    LEFT JOIN StatementEntity \n"
                + "\t            ON statementUid = (SELECT statementUid \n"
                + "                                     FROM StatementEntity \n"
                + "                                            LEFT JOIN ClazzAssignment \n"
                + "                                            ON ClazzAssignment.caUid = ClazzAssignmentContentJoin.cacjAssignmentUid \n"
                + "                                              JOIN CourseBlock\n"
                + "                                                ON CourseBlock.cbEntityUid = ClazzAssignment.caUid\n"
                + "                                               AND CourseBlock.cbType = 103 \n"
                + "                                    WHERE StatementEntity.statementContentEntryUid = ClazzAssignmentContentJoin.cacjContentUid\n"
                + "                                      AND StatementEntity.statementPersonUid = ClazzEnrolment.clazzEnrolmentPersonUid\n"
                + "                                      AND StatementEntity.contentEntryRoot  \n"
                + "                                      AND StatementEntity.timestamp \n"
                + "                                            BETWEEN CourseBlock.cbHideUntilDate\n"
                + "                                            AND CourseBlock.cbGracePeriodDate\n"
                + "                                  ORDER BY CASE WHEN StatementEntity.timestamp > CourseBlock.cbDeadlineDate \n"
                + "                                                THEN StatementEntity.resultScoreScaled * (1 - (CAST(CourseBlock.cbLateSubmissionPenalty AS REAL)/100))\n"
                + "                                                ELSE StatementEntity.resultScoreScaled END DESC, \n"
                + "                                            StatementEntity.extensionProgress DESC, \n"
                + "                                            StatementEntity.resultSuccess DESC LIMIT 1)      \n"
                + "                LEFT JOIN ClazzAssignmentRollUp\n"
                + "                ON ClazzAssignmentRollUp.cacheContentEntryUid = ClazzAssignmentContentJoin.cacjContentUid \n"
                + "                AND ClazzAssignmentRollUp.cachePersonUid = ClazzEnrolment.clazzEnrolmentPersonUid\n"
                + "                AND ClazzAssignmentRollUp.cacheClazzAssignmentUid = ClazzAssignment.caUid\n"
                + "                                            \n"
                + "                                            \n"
                + "\t     WHERE ClazzEnrolment.clazzEnrolmentRole = 1000\n"
                + "           AND ClazzEnrolment.clazzEnrolmentOutcome = 200\n"
                + "           AND ClazzEnrolment.clazzEnrolmentActive\n"
                + "           AND ClazzAssignment.caActive\n"
                + "           AND ClazzAssignmentContentJoin.cacjActive\n"
                + "           AND (? = 0 OR ClazzAssignment.caClazzUid = ?)\n"
                + "           AND (? = 0 OR ClazzAssignment.caUid = ?)\n"
                + "           AND (? = 0 OR ClazzEnrolment.clazzEnrolmentPersonUid = ?)\n"
                + "           AND (COALESCE(StatementEntity.resultScoreRaw,0) >= COALESCE(ClazzAssignmentRollUp.cacheStudentScore,0)\n"
                + "                    AND COALESCE(StatementEntity.extensionProgress,0) >= COALESCE(ClazzAssignmentRollUp.cacheProgress,0)\n"
                + "                    AND COALESCE(StatementEntity.resultSuccess,0) >= COALESCE(ClazzAssignmentRollUp.cacheSuccess,0))\n"
                + "      GROUP BY cacheClazzAssignmentUid, cacheContentEntryUid, cachePersonUid\n"
                + "         UNION \n"
                + "         SELECT clazzEnrolmentPersonUid AS cachePersonUid, \n"
                + "                0 AS cacheContentEntryUid, \n"
                + "                caUid AS cacheClazzAssignmentUid, \n"
                + "                COALESCE(MarkingStatement.resultScoreRaw,0) AS cacheStudentScore, \n"
                + "                COALESCE(cbMaxPoints,0) AS cacheMaxScore,\n"
                + "                0 AS cacheWeight,\n"
                + "                \n"
                + "                COALESCE(MarkingStatement.extensionProgress,0) AS cacheProgress,\n"
                + "                COALESCE(MarkingStatement.resultCompletion,'FALSE') AS cacheContentComplete, \n"
                + "                COALESCE(MarkingStatement.resultSuccess,0) AS cacheSuccess,\n"
                + "                (CASE WHEN SubmissionStatement.timestamp > CourseBlock.cbDeadlineDate \n"
                + "                     THEN CourseBlock.cbLateSubmissionPenalty \n"
                + "                     ELSE 0 END) AS cachePenalty,\n"
                + "                     \n"
                + "              (CASE WHEN SubmissionStatement.timestamp > CourseBlock.cbDeadlineDate \n"
                + "                     THEN (COALESCE(CAST(MarkingStatement.resultScoreRaw AS REAL),0) / COALESCE(CourseBlock.cbMaxPoints,0) * \n"
                + "                            100 * (1 - (CAST(cbLateSubmissionPenalty AS REAL)/100)))\n"
                + "                     ELSE (COALESCE(CAST(MarkingStatement.resultScoreRaw AS REAL),0) / COALESCE(cbMaxPoints,0) * \n"
                + "                            100)  END) AS cacheFinalWeightScoreWithPenalty, \n"
                + "                     \n"
                + "                   \n"
                + "               0 AS lastCsnChecked\n"
                + "         FROM ClazzAssignment\n"
                + "              JOIN ClazzEnrolment\n"
                + "              ON ClazzEnrolment.clazzEnrolmentClazzUid = ClazzAssignment.caClazzUid\n"
                + "              \n"
                + "               JOIN CourseBlock\n"
                + "                ON CourseBlock.cbEntityUid = ClazzAssignment.caUid\n"
                + "               AND CourseBlock.cbType = 103 \n"
                + "              \n"
                + "              LEFT JOIN StatementEntity AS SubmissionStatement\n"
                + "\t          ON SubmissionStatement.statementUid = (SELECT statementUid \n"
                + "                                   FROM StatementEntity\n"
                + "                                  WHERE StatementEntity.statementContentEntryUid = 0\n"
                + "                                    AND xObjectUid = ClazzAssignment.caXObjectUid\n"
                + "                                    AND StatementEntity.statementPersonUid = ClazzEnrolment.clazzEnrolmentPersonUid\n"
                + "                                    AND StatementEntity.timestamp \n"
                + "                                        BETWEEN CourseBlock.cbHideUntilDate\n"
                + "                                        AND CourseBlock.cbGracePeriodDate\n"
                + "                               ORDER BY timestamp DESC LIMIT 1\n"
                + "                                  )\n"
                + "              LEFT JOIN XObjectEntity AS ObjectStatementRef\n"
                + "              ON ObjectStatementRef.objectStatementRefUid = SubmissionStatement.statementUid                    \n"
                + "                                  \n"
                + "              LEFT JOIN StatementEntity AS MarkingStatement\n"
                + "               ON MarkingStatement.timestamp = (SELECT timestamp \n"
                + "                                                  FROM StatementEntity \n"
                + "                                                 WHERE xObjectUid = ObjectStatementRef.xObjectUid \n"
                + "                                              ORDER BY timestamp DESC \n"
                + "                                                 LIMIT 1)\n"
                + "              \n"
                + "        WHERE ClazzEnrolment.clazzEnrolmentRole = 1000\n"
                + "          AND ClazzEnrolment.clazzEnrolmentOutcome = 200\n"
                + "          AND ClazzEnrolment.clazzEnrolmentActive\n"
                + "          AND ClazzAssignment.caActive\n"
                + "          AND ClazzAssignment.caRequireFileSubmission\n"
                + "          AND (? = 0 OR ClazzAssignment.caClazzUid = ?)\n"
                + "          AND (? = 0 OR ClazzAssignment.caUid = ?)\n"
                + "          AND (? = 0 OR ClazzEnrolment.clazzEnrolmentPersonUid = ?)\n"
                + "      GROUP BY cacheClazzAssignmentUid, cacheContentEntryUid, cachePersonUid     \n"
                + "    ";
        return _query;
      }
    };
    this.__preparedStmtOfDeleteCachedInactiveContent = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + "        DELETE\n"
                + "         FROM ClazzAssignmentRollUp\n"
                + "        WHERE cacheContentEntryUid \n"
                + "                IN (SELECT cacjContentUid \n"
                + "                     FROM ClazzAssignmentContentJoin\n"
                + "                    WHERE NOT cacjActive)\n"
                + "           OR (cacheClazzAssignmentUid \n"
                + "              IN (SELECT caUid \n"
                + "                   FROM ClazzAssignment\n"
                + "                  WHERE caUid = ?\n"
                + "                    AND NOT caRequireFileSubmission) \n"
                + "               AND cacheContentEntryUid = 0)                                        \n"
                + "    ";
        return _query;
      }
    };
    this.__preparedStmtOfInvalidateCacheByAssignment = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + "        UPDATE ClazzAssignmentRollUp \n"
                + "           SET lastCsnChecked = 0\n"
                + "         WHERE cacheClazzAssignmentUid = ?\n"
                + "    ";
        return _query;
      }
    };
  }

  @Override
  public long insert(final ClazzAssignmentRollUp entity) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      long _result = __insertionAdapterOfClazzAssignmentRollUp.insertAndReturnId(entity);
      __db.setTransactionSuccessful();
      return _result;
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public Object insertAsync(final ClazzAssignmentRollUp entity,
      final Continuation<? super Long> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Long>() {
      @Override
      public Long call() throws Exception {
        __db.beginTransaction();
        try {
          long _result = __insertionAdapterOfClazzAssignmentRollUp.insertAndReturnId(entity);
          __db.setTransactionSuccessful();
          return _result;
        } finally {
          __db.endTransaction();
        }
      }
    }, continuation);
  }

  @Override
  public void insertList(final List<? extends ClazzAssignmentRollUp> entityList) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      __insertionAdapterOfClazzAssignmentRollUp.insert(entityList);
      __db.setTransactionSuccessful();
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public void updateList(final List<? extends ClazzAssignmentRollUp> entityList) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      __updateAdapterOfClazzAssignmentRollUp.handleMultiple(entityList);
      __db.setTransactionSuccessful();
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public void update(final ClazzAssignmentRollUp entity) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      __updateAdapterOfClazzAssignmentRollUp.handle(entity);
      __db.setTransactionSuccessful();
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public Object cacheBestStatements(final long clazzUid, final long assignmentUid,
      final long personUid, final Continuation<? super Unit> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Unit>() {
      @Override
      public Unit call() throws Exception {
        final SupportSQLiteStatement _stmt = __preparedStmtOfCacheBestStatements.acquire();
        int _argIndex = 1;
        _stmt.bindLong(_argIndex, clazzUid);
        _argIndex = 2;
        _stmt.bindLong(_argIndex, clazzUid);
        _argIndex = 3;
        _stmt.bindLong(_argIndex, assignmentUid);
        _argIndex = 4;
        _stmt.bindLong(_argIndex, assignmentUid);
        _argIndex = 5;
        _stmt.bindLong(_argIndex, personUid);
        _argIndex = 6;
        _stmt.bindLong(_argIndex, personUid);
        _argIndex = 7;
        _stmt.bindLong(_argIndex, clazzUid);
        _argIndex = 8;
        _stmt.bindLong(_argIndex, clazzUid);
        _argIndex = 9;
        _stmt.bindLong(_argIndex, assignmentUid);
        _argIndex = 10;
        _stmt.bindLong(_argIndex, assignmentUid);
        _argIndex = 11;
        _stmt.bindLong(_argIndex, personUid);
        _argIndex = 12;
        _stmt.bindLong(_argIndex, personUid);
        __db.beginTransaction();
        try {
          _stmt.executeInsert();
          __db.setTransactionSuccessful();
          return Unit.INSTANCE;
        } finally {
          __db.endTransaction();
          __preparedStmtOfCacheBestStatements.release(_stmt);
        }
      }
    }, continuation);
  }

  @Override
  public Object deleteCachedInactiveContent(final long caUid,
      final Continuation<? super Unit> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Unit>() {
      @Override
      public Unit call() throws Exception {
        final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteCachedInactiveContent.acquire();
        int _argIndex = 1;
        _stmt.bindLong(_argIndex, caUid);
        __db.beginTransaction();
        try {
          _stmt.executeUpdateDelete();
          __db.setTransactionSuccessful();
          return Unit.INSTANCE;
        } finally {
          __db.endTransaction();
          __preparedStmtOfDeleteCachedInactiveContent.release(_stmt);
        }
      }
    }, continuation);
  }

  @Override
  public Object invalidateCacheByAssignment(final long changedAssignmentUid,
      final Continuation<? super Unit> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Unit>() {
      @Override
      public Unit call() throws Exception {
        final SupportSQLiteStatement _stmt = __preparedStmtOfInvalidateCacheByAssignment.acquire();
        int _argIndex = 1;
        _stmt.bindLong(_argIndex, changedAssignmentUid);
        __db.beginTransaction();
        try {
          _stmt.executeUpdateDelete();
          __db.setTransactionSuccessful();
          return Unit.INSTANCE;
        } finally {
          __db.endTransaction();
          __preparedStmtOfInvalidateCacheByAssignment.release(_stmt);
        }
      }
    }, continuation);
  }

  @Override
  public Object invalidateCacheByAssignmentList(final List<Long> changedAssignmentUid,
      final Continuation<? super Unit> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Unit>() {
      @Override
      public Unit call() throws Exception {
        StringBuilder _stringBuilder = StringUtil.newStringBuilder();
        _stringBuilder.append("\n");
        _stringBuilder.append("        UPDATE ClazzAssignmentRollUp ");
        _stringBuilder.append("\n");
        _stringBuilder.append("           SET lastCsnChecked = 0");
        _stringBuilder.append("\n");
        _stringBuilder.append("         WHERE cacheClazzAssignmentUid IN (");
        final int _inputSize = changedAssignmentUid.size();
        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
        _stringBuilder.append(")");
        _stringBuilder.append("\n");
        _stringBuilder.append("    ");
        final String _sql = _stringBuilder.toString();
        final SupportSQLiteStatement _stmt = __db.compileStatement(_sql);
        int _argIndex = 1;
        for (long _item : changedAssignmentUid) {
          _stmt.bindLong(_argIndex, _item);
          _argIndex ++;
        }
        __db.beginTransaction();
        try {
          _stmt.executeUpdateDelete();
          __db.setTransactionSuccessful();
          return Unit.INSTANCE;
        } finally {
          __db.endTransaction();
        }
      }
    }, continuation);
  }

  public static List<Class<?>> getRequiredConverters() {
    return Collections.emptyList();
  }
}
