package com.ustadmobile.core.db.dao;

import android.database.Cursor;
import android.os.CancellationSignal;
import androidx.lifecycle.LiveData;
import androidx.room.CoroutinesRoom;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.SharedSQLiteStatement;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.ustadmobile.lib.db.entities.CourseAssignmentMark;
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.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 CourseAssignmentMarkDao_Impl extends CourseAssignmentMarkDao {
  private final RoomDatabase __db;

  private final EntityInsertionAdapter<CourseAssignmentMark> __insertionAdapterOfCourseAssignmentMark;

  private final EntityDeletionOrUpdateAdapter<CourseAssignmentMark> __updateAdapterOfCourseAssignmentMark;

  private final SharedSQLiteStatement __preparedStmtOfReplicateOnNewNode;

  private final SharedSQLiteStatement __preparedStmtOfReplicateOnChange;

  public CourseAssignmentMarkDao_Impl(RoomDatabase __db) {
    this.__db = __db;
    this.__insertionAdapterOfCourseAssignmentMark = new EntityInsertionAdapter<CourseAssignmentMark>(__db) {
      @Override
      public String createQuery() {
        return "INSERT OR ABORT INTO `CourseAssignmentMark` (`camUid`,`camAssignmentUid`,`camSubmitterUid`,`camMark`,`camPenalty`,`camLct`) VALUES (nullif(?, 0),?,?,?,?,?)";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, CourseAssignmentMark value) {
        stmt.bindLong(1, value.getCamUid());
        stmt.bindLong(2, value.getCamAssignmentUid());
        stmt.bindLong(3, value.getCamSubmitterUid());
        stmt.bindDouble(4, value.getCamMark());
        stmt.bindLong(5, value.getCamPenalty());
        stmt.bindLong(6, value.getCamLct());
      }
    };
    this.__updateAdapterOfCourseAssignmentMark = new EntityDeletionOrUpdateAdapter<CourseAssignmentMark>(__db) {
      @Override
      public String createQuery() {
        return "UPDATE OR ABORT `CourseAssignmentMark` SET `camUid` = ?,`camAssignmentUid` = ?,`camSubmitterUid` = ?,`camMark` = ?,`camPenalty` = ?,`camLct` = ? WHERE `camUid` = ?";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, CourseAssignmentMark value) {
        stmt.bindLong(1, value.getCamUid());
        stmt.bindLong(2, value.getCamAssignmentUid());
        stmt.bindLong(3, value.getCamSubmitterUid());
        stmt.bindDouble(4, value.getCamMark());
        stmt.bindLong(5, value.getCamPenalty());
        stmt.bindLong(6, value.getCamLct());
        stmt.bindLong(7, value.getCamUid());
      }
    };
    this.__preparedStmtOfReplicateOnNewNode = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + "     REPLACE INTO CourseAssignmentMarkReplicate(camPk, camDestination)\n"
                + "      SELECT DISTINCT CourseAssignmentMark.camUid AS camPk,\n"
                + "             ? AS camDestination\n"
                + "        FROM UserSession\n"
                + "             JOIN PersonGroupMember \n"
                + "                    ON UserSession.usPersonUid = PersonGroupMember.groupMemberPersonUid\n"
                + "             \n"
                + "               JOIN ScopedGrant\n"
                + "                    ON ScopedGrant.sgGroupUid = PersonGroupMember.groupMemberGroupUid\n"
                + "                        AND (ScopedGrant.sgPermissions & \n"
                + "        \n"
                + "                    8388608 \n"
                + "                    \n"
                + "                       ) > 0\n"
                + "               JOIN Clazz \n"
                + "                    ON \n"
                + "            ((ScopedGrant.sgTableId = -2\n"
                + "                                AND ScopedGrant.sgEntityUid = -2)\n"
                + "                            OR (ScopedGrant.sgTableId = 6\n"
                + "                                AND ScopedGrant.sgEntityUid = Clazz.clazzUid)\n"
                + "                            OR (ScopedGrant.sgTableId = 164\n"
                + "                                AND ScopedGrant.sgEntityUid = Clazz.clazzSchoolUid))\n"
                + "        \n"
                + "        \n"
                + "               JOIN ClazzAssignment\n"
                + "                    ON ClazzAssignment.caClazzUid = Clazz.clazzUid                \n"
                + "             JOIN CourseAssignmentMark\n"
                + "                    ON CourseAssignmentMark.camAssignmentUid = ClazzAssignment.caUid\n"
                + "                    \n"
                + "       WHERE UserSession.usClientNodeId = ?\n"
                + "         AND UserSession.usStatus = 1\n"
                + "         AND CourseAssignmentMark.camLct != COALESCE(\n"
                + "             (SELECT camVersionId\n"
                + "                FROM CourseAssignmentMarkReplicate\n"
                + "               WHERE camPk = CourseAssignmentMark.camUid\n"
                + "                 AND camDestination = ?), 0) \n"
                + "      /*psql ON CONFLICT(camPk, camDestination) DO UPDATE\n"
                + "             SET camPending = true\n"
                + "      */       \n"
                + "    ";
        return _query;
      }
    };
    this.__preparedStmtOfReplicateOnChange = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + " REPLACE INTO CourseAssignmentMarkReplicate(camPk, camDestination)\n"
                + "  SELECT DISTINCT CourseAssignmentMark.camUid AS camPk,\n"
                + "         UserSession.usClientNodeId AS camDestination\n"
                + "    FROM ChangeLog\n"
                + "         JOIN CourseAssignmentMark\n"
                + "             ON ChangeLog.chTableId = 523\n"
                + "                AND ChangeLog.chEntityPk = CourseAssignmentMark.camUid\n"
                + "             JOIN ClazzAssignment\n"
                + "                    ON CourseAssignmentMark.camAssignmentUid = ClazzAssignment.caUid\n"
                + "             JOIN Clazz\n"
                + "                    ON  Clazz.clazzUid = ClazzAssignment.caClazzUid\n"
                + "         \n"
                + "            JOIN ScopedGrant\n"
                + "                 ON \n"
                + "            ((ScopedGrant.sgTableId = -2\n"
                + "                                AND ScopedGrant.sgEntityUid = -2)\n"
                + "                            OR (ScopedGrant.sgTableId = 6\n"
                + "                                AND ScopedGrant.sgEntityUid = Clazz.clazzUid)\n"
                + "                            OR (ScopedGrant.sgTableId = 164\n"
                + "                                AND ScopedGrant.sgEntityUid = Clazz.clazzSchoolUid))\n"
                + "        \n"
                + "                    AND (ScopedGrant.sgPermissions & \n"
                + "        \n"
                + "              8388608\n"
                + "              \n"
                + "              \n"
                + "                                                       ) > 0\n"
                + "             JOIN PersonGroupMember AS PrsGrpMbr\n"
                + "                   ON ScopedGrant.sgGroupUid = PrsGrpMbr.groupMemberGroupUid\n"
                + "                                               \n"
                + "              JOIN UserSession\n"
                + "                   ON UserSession.usPersonUid = PrsGrpMbr.groupMemberPersonUid\n"
                + "                      AND UserSession.usStatus = 1\n"
                + "          \n"
                + "   WHERE UserSession.usClientNodeId != (\n"
                + "         SELECT nodeClientId \n"
                + "           FROM SyncNode\n"
                + "          LIMIT 1)\n"
                + "     AND CourseAssignmentMark.camLct != COALESCE(\n"
                + "         (SELECT camVersionId\n"
                + "            FROM CourseAssignmentMarkReplicate\n"
                + "           WHERE camPk = CourseAssignmentMark.camUid\n"
                + "             AND camDestination = UserSession.usClientNodeId), 0)\n"
                + " /*psql ON CONFLICT(camPk, camDestination) DO UPDATE\n"
                + "     SET camPending = true\n"
                + "  */               \n"
                + " ";
        return _query;
      }
    };
  }

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

  @Override
  public Object insertAsync(final CourseAssignmentMark 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 = __insertionAdapterOfCourseAssignmentMark.insertAndReturnId(entity);
          __db.setTransactionSuccessful();
          return _result;
        } finally {
          __db.endTransaction();
        }
      }
    }, continuation);
  }

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

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

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

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

  @Override
  public Object replicateOnChange(final Continuation<? super Unit> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Unit>() {
      @Override
      public Unit call() throws Exception {
        final SupportSQLiteStatement _stmt = __preparedStmtOfReplicateOnChange.acquire();
        __db.beginTransaction();
        try {
          _stmt.executeInsert();
          __db.setTransactionSuccessful();
          return Unit.INSTANCE;
        } finally {
          __db.endTransaction();
          __preparedStmtOfReplicateOnChange.release(_stmt);
        }
      }
    }, continuation);
  }

  @Override
  public LiveData<CourseAssignmentMark> getMarkOfAssignmentForSubmitterLiveData(
      final long assignmentUid, final long submitterUid) {
    final String _sql = "\n"
            + "        SELECT * \n"
            + "          FROM CourseAssignmentMark               \n"
            + "         WHERE camAssignmentUid = ?\n"
            + "           AND camSubmitterUid = ?\n"
            + "      ORDER BY camLct DESC\n"
            + "         LIMIT 1\n"
            + "    ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 2);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, assignmentUid);
    _argIndex = 2;
    _statement.bindLong(_argIndex, submitterUid);
    return __db.getInvalidationTracker().createLiveData(new String[]{"CourseAssignmentMark"}, false, new Callable<CourseAssignmentMark>() {
      @Override
      public CourseAssignmentMark call() throws Exception {
        final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
        try {
          final int _cursorIndexOfCamUid = CursorUtil.getColumnIndexOrThrow(_cursor, "camUid");
          final int _cursorIndexOfCamAssignmentUid = CursorUtil.getColumnIndexOrThrow(_cursor, "camAssignmentUid");
          final int _cursorIndexOfCamSubmitterUid = CursorUtil.getColumnIndexOrThrow(_cursor, "camSubmitterUid");
          final int _cursorIndexOfCamMark = CursorUtil.getColumnIndexOrThrow(_cursor, "camMark");
          final int _cursorIndexOfCamPenalty = CursorUtil.getColumnIndexOrThrow(_cursor, "camPenalty");
          final int _cursorIndexOfCamLct = CursorUtil.getColumnIndexOrThrow(_cursor, "camLct");
          final CourseAssignmentMark _result;
          if(_cursor.moveToFirst()) {
            _result = new CourseAssignmentMark();
            final long _tmpCamUid;
            _tmpCamUid = _cursor.getLong(_cursorIndexOfCamUid);
            _result.setCamUid(_tmpCamUid);
            final long _tmpCamAssignmentUid;
            _tmpCamAssignmentUid = _cursor.getLong(_cursorIndexOfCamAssignmentUid);
            _result.setCamAssignmentUid(_tmpCamAssignmentUid);
            final long _tmpCamSubmitterUid;
            _tmpCamSubmitterUid = _cursor.getLong(_cursorIndexOfCamSubmitterUid);
            _result.setCamSubmitterUid(_tmpCamSubmitterUid);
            final float _tmpCamMark;
            _tmpCamMark = _cursor.getFloat(_cursorIndexOfCamMark);
            _result.setCamMark(_tmpCamMark);
            final int _tmpCamPenalty;
            _tmpCamPenalty = _cursor.getInt(_cursorIndexOfCamPenalty);
            _result.setCamPenalty(_tmpCamPenalty);
            final long _tmpCamLct;
            _tmpCamLct = _cursor.getLong(_cursorIndexOfCamLct);
            _result.setCamLct(_tmpCamLct);
          } else {
            _result = null;
          }
          return _result;
        } finally {
          _cursor.close();
        }
      }

      @Override
      protected void finalize() {
        _statement.release();
      }
    });
  }

  @Override
  public CourseAssignmentMark getMarkOfAssignmentForStudent(final long assignmentUid,
      final long submitterUid) {
    final String _sql = "\n"
            + "        SELECT * \n"
            + "          FROM CourseAssignmentMark\n"
            + "         WHERE camAssignmentUid = ?\n"
            + "           AND camSubmitterUid = ?\n"
            + "      ORDER BY camLct DESC\n"
            + "         LIMIT 1\n"
            + "    ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 2);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, assignmentUid);
    _argIndex = 2;
    _statement.bindLong(_argIndex, submitterUid);
    __db.assertNotSuspendingTransaction();
    final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
    try {
      final int _cursorIndexOfCamUid = CursorUtil.getColumnIndexOrThrow(_cursor, "camUid");
      final int _cursorIndexOfCamAssignmentUid = CursorUtil.getColumnIndexOrThrow(_cursor, "camAssignmentUid");
      final int _cursorIndexOfCamSubmitterUid = CursorUtil.getColumnIndexOrThrow(_cursor, "camSubmitterUid");
      final int _cursorIndexOfCamMark = CursorUtil.getColumnIndexOrThrow(_cursor, "camMark");
      final int _cursorIndexOfCamPenalty = CursorUtil.getColumnIndexOrThrow(_cursor, "camPenalty");
      final int _cursorIndexOfCamLct = CursorUtil.getColumnIndexOrThrow(_cursor, "camLct");
      final CourseAssignmentMark _result;
      if(_cursor.moveToFirst()) {
        _result = new CourseAssignmentMark();
        final long _tmpCamUid;
        _tmpCamUid = _cursor.getLong(_cursorIndexOfCamUid);
        _result.setCamUid(_tmpCamUid);
        final long _tmpCamAssignmentUid;
        _tmpCamAssignmentUid = _cursor.getLong(_cursorIndexOfCamAssignmentUid);
        _result.setCamAssignmentUid(_tmpCamAssignmentUid);
        final long _tmpCamSubmitterUid;
        _tmpCamSubmitterUid = _cursor.getLong(_cursorIndexOfCamSubmitterUid);
        _result.setCamSubmitterUid(_tmpCamSubmitterUid);
        final float _tmpCamMark;
        _tmpCamMark = _cursor.getFloat(_cursorIndexOfCamMark);
        _result.setCamMark(_tmpCamMark);
        final int _tmpCamPenalty;
        _tmpCamPenalty = _cursor.getInt(_cursorIndexOfCamPenalty);
        _result.setCamPenalty(_tmpCamPenalty);
        final long _tmpCamLct;
        _tmpCamLct = _cursor.getLong(_cursorIndexOfCamLct);
        _result.setCamLct(_tmpCamLct);
      } else {
        _result = null;
      }
      return _result;
    } finally {
      _cursor.close();
      _statement.release();
    }
  }

  @Override
  public Object findNextSubmitterToMarkForAssignment(final long assignmentUid,
      final long submitterUid, final Continuation<? super Long> continuation) {
    final String _sql = "\n"
            + "         SELECT COALESCE((\n"
            + "            SELECT casSubmitterUid\n"
            + "              FROM CourseAssignmentSubmission\n"
            + "              \n"
            + "                   LEFT JOIN CourseAssignmentMark\n"
            + "                   ON CourseAssignmentMark.camSubmitterUid = CourseAssignmentSubmission.casSubmitterUid\n"
            + "                   AND CourseAssignmentMark.camAssignmentUid = ?\n"
            + "                   \n"
            + "             WHERE CourseAssignmentSubmission.casSubmitterUid != ?\n"
            + "               AND CourseAssignmentMark.camUid IS NULL\n"
            + "          GROUP BY casSubmitterUid\n"
            + "         LIMIT 1),0)\n"
            + "    ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 2);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, assignmentUid);
    _argIndex = 2;
    _statement.bindLong(_argIndex, submitterUid);
    final CancellationSignal _cancellationSignal = DBUtil.createCancellationSignal();
    return CoroutinesRoom.execute(__db, false, _cancellationSignal, new Callable<Long>() {
      @Override
      public Long call() throws Exception {
        final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
        try {
          final Long _result;
          if(_cursor.moveToFirst()) {
            final long _tmp;
            _tmp = _cursor.getLong(0);
            _result = _tmp;
          } else {
            _result = 0L;
          }
          return _result;
        } finally {
          _cursor.close();
          _statement.release();
        }
      }
    }, continuation);
  }

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