package com.ustadmobile.core.db.dao;

import android.database.Cursor;
import android.os.CancellationSignal;
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.DBUtil;
import androidx.room.util.StringUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.ustadmobile.lib.db.entities.ClazzContentJoin;
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.ArrayList;
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 ClazzContentJoinDao_Impl extends ClazzContentJoinDao {
  private final RoomDatabase __db;

  private final EntityInsertionAdapter<ClazzContentJoin> __insertionAdapterOfClazzContentJoin;

  private final EntityDeletionOrUpdateAdapter<ClazzContentJoin> __updateAdapterOfClazzContentJoin;

  private final SharedSQLiteStatement __preparedStmtOfReplicateOnNewNode;

  private final SharedSQLiteStatement __preparedStmtOfReplicateOnChange;

  public ClazzContentJoinDao_Impl(RoomDatabase __db) {
    this.__db = __db;
    this.__insertionAdapterOfClazzContentJoin = new EntityInsertionAdapter<ClazzContentJoin>(__db) {
      @Override
      public String createQuery() {
        return "INSERT OR ABORT INTO `ClazzContentJoin` (`ccjUid`,`ccjContentEntryUid`,`ccjClazzUid`,`ccjActive`,`ccjLocalChangeSeqNum`,`ccjMasterChangeSeqNum`,`ccjLastChangedBy`,`ccjLct`) VALUES (nullif(?, 0),?,?,?,?,?,?,?)";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, ClazzContentJoin value) {
        stmt.bindLong(1, value.getCcjUid());
        stmt.bindLong(2, value.getCcjContentEntryUid());
        stmt.bindLong(3, value.getCcjClazzUid());
        final int _tmp = value.getCcjActive() ? 1 : 0;
        stmt.bindLong(4, _tmp);
        stmt.bindLong(5, value.getCcjLocalChangeSeqNum());
        stmt.bindLong(6, value.getCcjMasterChangeSeqNum());
        stmt.bindLong(7, value.getCcjLastChangedBy());
        stmt.bindLong(8, value.getCcjLct());
      }
    };
    this.__updateAdapterOfClazzContentJoin = new EntityDeletionOrUpdateAdapter<ClazzContentJoin>(__db) {
      @Override
      public String createQuery() {
        return "UPDATE OR ABORT `ClazzContentJoin` SET `ccjUid` = ?,`ccjContentEntryUid` = ?,`ccjClazzUid` = ?,`ccjActive` = ?,`ccjLocalChangeSeqNum` = ?,`ccjMasterChangeSeqNum` = ?,`ccjLastChangedBy` = ?,`ccjLct` = ? WHERE `ccjUid` = ?";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, ClazzContentJoin value) {
        stmt.bindLong(1, value.getCcjUid());
        stmt.bindLong(2, value.getCcjContentEntryUid());
        stmt.bindLong(3, value.getCcjClazzUid());
        final int _tmp = value.getCcjActive() ? 1 : 0;
        stmt.bindLong(4, _tmp);
        stmt.bindLong(5, value.getCcjLocalChangeSeqNum());
        stmt.bindLong(6, value.getCcjMasterChangeSeqNum());
        stmt.bindLong(7, value.getCcjLastChangedBy());
        stmt.bindLong(8, value.getCcjLct());
        stmt.bindLong(9, value.getCcjUid());
      }
    };
    this.__preparedStmtOfReplicateOnNewNode = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + "     REPLACE INTO ClazzContentJoinReplicate(ccjPk, ccjDestination)\n"
                + "      SELECT DISTINCT ClazzContentJoin.ccjUid AS ccjUid,\n"
                + "             ? AS ccjDestination\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"
                + "                    4398046511104 \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 ClazzContentJoin    \n"
                + "                    ON Clazz.clazzUid = ClazzContentJoin.ccjClazzUid\n"
                + "       WHERE UserSession.usClientNodeId = ? \n"
                + "         AND UserSession.usStatus = 1             \n"
                + "         AND ClazzContentJoin.ccjLct != COALESCE(\n"
                + "             (SELECT ccjVersionId\n"
                + "                FROM ClazzContentJoinReplicate\n"
                + "               WHERE ccjPk = ClazzContentJoin.ccjUid\n"
                + "                 AND ccjDestination = ?), 0) \n"
                + "      /*psql ON CONFLICT(ccjPk, ccjDestination) DO UPDATE\n"
                + "             SET ccjPending = true\n"
                + "      */       \n"
                + "    ";
        return _query;
      }
    };
    this.__preparedStmtOfReplicateOnChange = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + " REPLACE INTO ClazzContentJoinReplicate(ccjPk, ccjDestination)\n"
                + "  SELECT DISTINCT ClazzContentJoin.ccjUid AS ccjUid,\n"
                + "         UserSession.usClientNodeId AS ccjDestination\n"
                + "    FROM ChangeLog\n"
                + "         JOIN ClazzContentJoin\n"
                + "             ON ChangeLog.chTableId = 134\n"
                + "                AND ChangeLog.chEntityPk = ClazzContentJoin.ccjUid\n"
                + "         JOIN Clazz \n"
                + "              ON Clazz.clazzUid = ClazzContentJoin.ccjClazzUid                \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"
                + "              4398046511104\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 ClazzContentJoin.ccjLct != COALESCE(\n"
                + "         (SELECT ccjVersionId\n"
                + "            FROM ClazzContentJoinReplicate\n"
                + "           WHERE ccjPk = ClazzContentJoin.ccjUid\n"
                + "             AND ccjDestination = UserSession.usClientNodeId), 0)\n"
                + " /*psql ON CONFLICT(ccjPk, ccjDestination) DO UPDATE\n"
                + "     SET ccjPending = true\n"
                + "  */               \n"
                + "    ";
        return _query;
      }
    };
  }

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

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

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

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

  @Override
  public void update(final ClazzContentJoin entity) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      __updateAdapterOfClazzContentJoin.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 Object listOfEntriesInClazz(final long clazzUid,
      final Continuation<? super List<Long>> continuation) {
    final String _sql = "\n"
            + "        SELECT ccjContentEntryUid \n"
            + "          FROM ClazzContentJoin\n"
            + "         WHERE ccjClazzUid = ?\n"
            + "           AND ccjActive\n"
            + "    ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, clazzUid);
    final CancellationSignal _cancellationSignal = DBUtil.createCancellationSignal();
    return CoroutinesRoom.execute(__db, false, _cancellationSignal, new Callable<List<Long>>() {
      @Override
      public List<Long> call() throws Exception {
        final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
        try {
          final List<Long> _result = new ArrayList<Long>(_cursor.getCount());
          while(_cursor.moveToNext()) {
            final Long _item;
            _item = _cursor.getLong(0);
            _result.add(_item);
          }
          return _result;
        } finally {
          _cursor.close();
          _statement.release();
        }
      }
    }, continuation);
  }

  @Override
  public Object toggleVisibilityClazzContent(final boolean toggleVisibility,
      final List<Long> selectedItem, final long changedTime,
      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("UPDATE ClazzContentJoin ");
        _stringBuilder.append("\n");
        _stringBuilder.append("                       SET ccjActive = ");
        _stringBuilder.append("?");
        _stringBuilder.append(", ");
        _stringBuilder.append("\n");
        _stringBuilder.append("                           ccjLct = ");
        _stringBuilder.append("?");
        _stringBuilder.append(" ");
        _stringBuilder.append("\n");
        _stringBuilder.append("                     WHERE ccjContentEntryUid IN (");
        final int _inputSize = selectedItem.size();
        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
        _stringBuilder.append(")");
        final String _sql = _stringBuilder.toString();
        final SupportSQLiteStatement _stmt = __db.compileStatement(_sql);
        int _argIndex = 1;
        final int _tmp = toggleVisibility ? 1 : 0;
        _stmt.bindLong(_argIndex, _tmp);
        _argIndex = 2;
        _stmt.bindLong(_argIndex, changedTime);
        _argIndex = 3;
        for (long _item : selectedItem) {
          _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();
  }
}
