package com.ustadmobile.core.db.dao;

import android.database.Cursor;
import android.os.CancellationSignal;
import androidx.paging.DataSource;
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.paging.LimitOffsetDataSource;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.ustadmobile.lib.db.entities.CourseGroupSet;
import java.lang.Class;
import java.lang.Exception;
import java.lang.Integer;
import java.lang.Long;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
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 CourseGroupSetDao_Impl extends CourseGroupSetDao {
  private final RoomDatabase __db;

  private final EntityInsertionAdapter<CourseGroupSet> __insertionAdapterOfCourseGroupSet;

  private final EntityDeletionOrUpdateAdapter<CourseGroupSet> __updateAdapterOfCourseGroupSet;

  private final SharedSQLiteStatement __preparedStmtOfReplicateOnNewNode;

  private final SharedSQLiteStatement __preparedStmtOfReplicateOnChange;

  public CourseGroupSetDao_Impl(RoomDatabase __db) {
    this.__db = __db;
    this.__insertionAdapterOfCourseGroupSet = new EntityInsertionAdapter<CourseGroupSet>(__db) {
      @Override
      public String createQuery() {
        return "INSERT OR ABORT INTO `CourseGroupSet` (`cgsUid`,`cgsName`,`cgsTotalGroups`,`cgsActive`,`cgsClazzUid`,`cgsLct`) VALUES (nullif(?, 0),?,?,?,?,?)";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, CourseGroupSet value) {
        stmt.bindLong(1, value.getCgsUid());
        if (value.getCgsName() == null) {
          stmt.bindNull(2);
        } else {
          stmt.bindString(2, value.getCgsName());
        }
        stmt.bindLong(3, value.getCgsTotalGroups());
        final int _tmp = value.getCgsActive() ? 1 : 0;
        stmt.bindLong(4, _tmp);
        stmt.bindLong(5, value.getCgsClazzUid());
        stmt.bindLong(6, value.getCgsLct());
      }
    };
    this.__updateAdapterOfCourseGroupSet = new EntityDeletionOrUpdateAdapter<CourseGroupSet>(__db) {
      @Override
      public String createQuery() {
        return "UPDATE OR ABORT `CourseGroupSet` SET `cgsUid` = ?,`cgsName` = ?,`cgsTotalGroups` = ?,`cgsActive` = ?,`cgsClazzUid` = ?,`cgsLct` = ? WHERE `cgsUid` = ?";
      }

      @Override
      public void bind(SupportSQLiteStatement stmt, CourseGroupSet value) {
        stmt.bindLong(1, value.getCgsUid());
        if (value.getCgsName() == null) {
          stmt.bindNull(2);
        } else {
          stmt.bindString(2, value.getCgsName());
        }
        stmt.bindLong(3, value.getCgsTotalGroups());
        final int _tmp = value.getCgsActive() ? 1 : 0;
        stmt.bindLong(4, _tmp);
        stmt.bindLong(5, value.getCgsClazzUid());
        stmt.bindLong(6, value.getCgsLct());
        stmt.bindLong(7, value.getCgsUid());
      }
    };
    this.__preparedStmtOfReplicateOnNewNode = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + "     REPLACE INTO CourseGroupSetReplicate(cgsPk, cgsDestination)\n"
                + "      SELECT DISTINCT CourseGroupSet.cgsUid AS cgsUid,\n"
                + "             ? AS cgsDestination\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"
                + "                    2 \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 CourseGroupSet\n"
                + "                    ON CourseGroupSet.cgsClazzUid = Clazz.clazzUid\n"
                + "       WHERE UserSession.usClientNodeId = ?\n"
                + "         AND UserSession.usStatus = 1\n"
                + "         AND CourseGroupSet.cgsLct != COALESCE(\n"
                + "             (SELECT cgsVersionId\n"
                + "                FROM CourseGroupSetReplicate\n"
                + "               WHERE cgsPk = CourseGroupSet.cgsUid\n"
                + "                 AND cgsDestination = ?), 0) \n"
                + "      /*psql ON CONFLICT(cgsPk, cgsDestination) DO UPDATE\n"
                + "             SET cgsPending = true\n"
                + "      */       \n"
                + "    ";
        return _query;
      }
    };
    this.__preparedStmtOfReplicateOnChange = new SharedSQLiteStatement(__db) {
      @Override
      public String createQuery() {
        final String _query = "\n"
                + " REPLACE INTO CourseGroupSetReplicate(cgsPk, cgsDestination)\n"
                + "  SELECT DISTINCT CourseGroupSet.cgsUid AS cgsUid,\n"
                + "         UserSession.usClientNodeId AS cgsDestination\n"
                + "    FROM ChangeLog\n"
                + "         JOIN CourseGroupSet\n"
                + "             ON ChangeLog.chTableId = 242\n"
                + "                AND ChangeLog.chEntityPk = CourseGroupSet.cgsUid\n"
                + "         JOIN Clazz \n"
                + "              ON Clazz.clazzUid = CourseGroupSet.cgsClazzUid \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 CourseGroupSet.cgsLct != COALESCE(\n"
                + "         (SELECT cgsVersionId\n"
                + "            FROM CourseGroupSetReplicate\n"
                + "           WHERE cgsPk = CourseGroupSet.cgsUid\n"
                + "             AND cgsDestination = UserSession.usClientNodeId), 0)\n"
                + " /*psql ON CONFLICT(cgsPk, cgsDestination) DO UPDATE\n"
                + "     SET cgsPending = true\n"
                + "  */               \n"
                + " ";
        return _query;
      }
    };
  }

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

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

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

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

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

  @Override
  public Object updateAsync(final CourseGroupSet entity,
      final Continuation<? super Integer> continuation) {
    return CoroutinesRoom.execute(__db, true, new Callable<Integer>() {
      @Override
      public Integer call() throws Exception {
        int _total = 0;
        __db.beginTransaction();
        try {
          _total +=__updateAdapterOfCourseGroupSet.handle(entity);
          __db.setTransactionSuccessful();
          return _total;
        } finally {
          __db.endTransaction();
        }
      }
    }, continuation);
  }

  @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 DataSource.Factory<Integer, CourseGroupSet> findAllCourseGroupSetForClazz(
      final long clazzUid) {
    final String _sql = "\n"
            + "        SELECT *\n"
            + "         FROM CourseGroupSet\n"
            + "        WHERE cgsActive\n"
            + "          AND cgsClazzUid = ?\n"
            + "     ORDER BY cgsName   \n"
            + "    ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, clazzUid);
    return new DataSource.Factory<Integer, CourseGroupSet>() {
      @Override
      public LimitOffsetDataSource<CourseGroupSet> create() {
        return new LimitOffsetDataSource<CourseGroupSet>(__db, _statement, false, true , "CourseGroupSet") {
          @Override
          protected List<CourseGroupSet> convertRows(Cursor cursor) {
            final int _cursorIndexOfCgsUid = CursorUtil.getColumnIndexOrThrow(cursor, "cgsUid");
            final int _cursorIndexOfCgsName = CursorUtil.getColumnIndexOrThrow(cursor, "cgsName");
            final int _cursorIndexOfCgsTotalGroups = CursorUtil.getColumnIndexOrThrow(cursor, "cgsTotalGroups");
            final int _cursorIndexOfCgsActive = CursorUtil.getColumnIndexOrThrow(cursor, "cgsActive");
            final int _cursorIndexOfCgsClazzUid = CursorUtil.getColumnIndexOrThrow(cursor, "cgsClazzUid");
            final int _cursorIndexOfCgsLct = CursorUtil.getColumnIndexOrThrow(cursor, "cgsLct");
            final List<CourseGroupSet> _res = new ArrayList<CourseGroupSet>(cursor.getCount());
            while(cursor.moveToNext()) {
              final CourseGroupSet _item;
              _item = new CourseGroupSet();
              final long _tmpCgsUid;
              _tmpCgsUid = cursor.getLong(_cursorIndexOfCgsUid);
              _item.setCgsUid(_tmpCgsUid);
              final String _tmpCgsName;
              if (cursor.isNull(_cursorIndexOfCgsName)) {
                _tmpCgsName = null;
              } else {
                _tmpCgsName = cursor.getString(_cursorIndexOfCgsName);
              }
              _item.setCgsName(_tmpCgsName);
              final int _tmpCgsTotalGroups;
              _tmpCgsTotalGroups = cursor.getInt(_cursorIndexOfCgsTotalGroups);
              _item.setCgsTotalGroups(_tmpCgsTotalGroups);
              final boolean _tmpCgsActive;
              final int _tmp;
              _tmp = cursor.getInt(_cursorIndexOfCgsActive);
              _tmpCgsActive = _tmp != 0;
              _item.setCgsActive(_tmpCgsActive);
              final long _tmpCgsClazzUid;
              _tmpCgsClazzUid = cursor.getLong(_cursorIndexOfCgsClazzUid);
              _item.setCgsClazzUid(_tmpCgsClazzUid);
              final long _tmpCgsLct;
              _tmpCgsLct = cursor.getLong(_cursorIndexOfCgsLct);
              _item.setCgsLct(_tmpCgsLct);
              _res.add(_item);
            }
            return _res;
          }
        };
      }
    };
  }

  @Override
  public List<CourseGroupSet> findAllCourseGroupSetForClazzList(final long clazzUid) {
    final String _sql = "\n"
            + "        SELECT *\n"
            + "         FROM CourseGroupSet\n"
            + "        WHERE cgsActive\n"
            + "          AND cgsClazzUid = ?\n"
            + "     ORDER BY cgsName   \n"
            + "    ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, clazzUid);
    __db.assertNotSuspendingTransaction();
    final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
    try {
      final int _cursorIndexOfCgsUid = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsUid");
      final int _cursorIndexOfCgsName = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsName");
      final int _cursorIndexOfCgsTotalGroups = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsTotalGroups");
      final int _cursorIndexOfCgsActive = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsActive");
      final int _cursorIndexOfCgsClazzUid = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsClazzUid");
      final int _cursorIndexOfCgsLct = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsLct");
      final List<CourseGroupSet> _result = new ArrayList<CourseGroupSet>(_cursor.getCount());
      while(_cursor.moveToNext()) {
        final CourseGroupSet _item;
        _item = new CourseGroupSet();
        final long _tmpCgsUid;
        _tmpCgsUid = _cursor.getLong(_cursorIndexOfCgsUid);
        _item.setCgsUid(_tmpCgsUid);
        final String _tmpCgsName;
        if (_cursor.isNull(_cursorIndexOfCgsName)) {
          _tmpCgsName = null;
        } else {
          _tmpCgsName = _cursor.getString(_cursorIndexOfCgsName);
        }
        _item.setCgsName(_tmpCgsName);
        final int _tmpCgsTotalGroups;
        _tmpCgsTotalGroups = _cursor.getInt(_cursorIndexOfCgsTotalGroups);
        _item.setCgsTotalGroups(_tmpCgsTotalGroups);
        final boolean _tmpCgsActive;
        final int _tmp;
        _tmp = _cursor.getInt(_cursorIndexOfCgsActive);
        _tmpCgsActive = _tmp != 0;
        _item.setCgsActive(_tmpCgsActive);
        final long _tmpCgsClazzUid;
        _tmpCgsClazzUid = _cursor.getLong(_cursorIndexOfCgsClazzUid);
        _item.setCgsClazzUid(_tmpCgsClazzUid);
        final long _tmpCgsLct;
        _tmpCgsLct = _cursor.getLong(_cursorIndexOfCgsLct);
        _item.setCgsLct(_tmpCgsLct);
        _result.add(_item);
      }
      return _result;
    } finally {
      _cursor.close();
      _statement.release();
    }
  }

  @Override
  public Object findByUidAsync(final long uid,
      final Continuation<? super CourseGroupSet> continuation) {
    final String _sql = "\n"
            + "        SELECT * \n"
            + "         FROM CourseGroupSet \n"
            + "        WHERE cgsUid = ?\n"
            + "        ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
    int _argIndex = 1;
    _statement.bindLong(_argIndex, uid);
    final CancellationSignal _cancellationSignal = DBUtil.createCancellationSignal();
    return CoroutinesRoom.execute(__db, false, _cancellationSignal, new Callable<CourseGroupSet>() {
      @Override
      public CourseGroupSet call() throws Exception {
        final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
        try {
          final int _cursorIndexOfCgsUid = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsUid");
          final int _cursorIndexOfCgsName = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsName");
          final int _cursorIndexOfCgsTotalGroups = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsTotalGroups");
          final int _cursorIndexOfCgsActive = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsActive");
          final int _cursorIndexOfCgsClazzUid = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsClazzUid");
          final int _cursorIndexOfCgsLct = CursorUtil.getColumnIndexOrThrow(_cursor, "cgsLct");
          final CourseGroupSet _result;
          if(_cursor.moveToFirst()) {
            _result = new CourseGroupSet();
            final long _tmpCgsUid;
            _tmpCgsUid = _cursor.getLong(_cursorIndexOfCgsUid);
            _result.setCgsUid(_tmpCgsUid);
            final String _tmpCgsName;
            if (_cursor.isNull(_cursorIndexOfCgsName)) {
              _tmpCgsName = null;
            } else {
              _tmpCgsName = _cursor.getString(_cursorIndexOfCgsName);
            }
            _result.setCgsName(_tmpCgsName);
            final int _tmpCgsTotalGroups;
            _tmpCgsTotalGroups = _cursor.getInt(_cursorIndexOfCgsTotalGroups);
            _result.setCgsTotalGroups(_tmpCgsTotalGroups);
            final boolean _tmpCgsActive;
            final int _tmp;
            _tmp = _cursor.getInt(_cursorIndexOfCgsActive);
            _tmpCgsActive = _tmp != 0;
            _result.setCgsActive(_tmpCgsActive);
            final long _tmpCgsClazzUid;
            _tmpCgsClazzUid = _cursor.getLong(_cursorIndexOfCgsClazzUid);
            _result.setCgsClazzUid(_tmpCgsClazzUid);
            final long _tmpCgsLct;
            _tmpCgsLct = _cursor.getLong(_cursorIndexOfCgsLct);
            _result.setCgsLct(_tmpCgsLct);
          } else {
            _result = null;
          }
          return _result;
        } finally {
          _cursor.close();
          _statement.release();
        }
      }
    }, continuation);
  }

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