import 'package:drift/drift.dart';
import 'package:sendtrain/database/database.dart';

part 'activities_dao.g.dart';

@DriftAccessor(tables: [Activities])
class ActivitiesDao extends DatabaseAccessor<AppDatabase>
    with _$ActivitiesDaoMixin {
  ActivitiesDao(super.db);

  Future<List<Activity>> all() async {
    return await select(activities).get();
  }

  Future<Activity> find(int id) async {
    return await (select(activities)
          ..where((activity) => activity.id.equals(id)))
        .getSingle();
  }

  Future remove(Activity activity) => delete(activities).delete(activity);

  Future<List<Activity>> contains(value) async {
    return (select(activities)
          ..where((t) =>
              t.title.contains(value) | t.description.contains(value) | t.category.contains(value)))
        .get();
  }

  Future<List<Activity>> activitiesFromSession(int id) async {
    final result = select(db.sessionActivities).join(
      [
        innerJoin(
          db.activities,
          db.activities.id.equalsExp(db.sessionActivities.activityId),
        ),
      ],
    )..where(db.sessionActivities.sessionId.equals(id));

    final activities =
        (await result.get()).map((e) => e.readTable(db.activities)).toList();

    return activities;
  }

  Stream<List<Activity>> watchSessionActivities(int id) {
    final query = select(db.sessionActivities).join(
      [
        innerJoin(
          db.activities,
          db.activities.id.equalsExp(db.sessionActivities.activityId),
        ),
      ],
    )..where(db.sessionActivities.sessionId.equals(id));

    return query.watch().map((rows) {
      final activities = (rows).map((e) => e.readTable(db.activities)).toList();

      return activities;
    });
  }

  // MultiSelectable<SessionActivity> _selectableSessionActivities(int id) {
  //   // return select(db.sessionActivities)..limit(1, offset: 1);
  //   // final query = select(db.sessionActivities).join(
  //   //   [
  //   //     innerJoin(
  //   //       db.activities,
  //   //       db.activities.id.equalsExp(db.sessionActivities.activityId),
  //   //     ),
  //   //   ],
  //   // )..where(db.sessionActivities.sessionId.equals(id));

  //   // return query;

  //   final query = select(db.sessionActivities)..where((row) => row.sessionId.equals(id));

  //   query.join(
  //     [
  //       innerJoin(
  //         db.activities,
  //         db.activities.id.equalsExp(db.sessionActivities.activityId),
  //       ),
  //     ],
  //   );

  //   return query;
  // }
}
