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

part 'actions_dao.g.dart';

@DriftAccessor(tables: [Actions])
class ActionsDao extends DatabaseAccessor<AppDatabase> with _$ActionsDaoMixin {
  ActionsDao(super.db);

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

  Future<Action> find(int id) async {
    return await (select(actions)..where((action) => action.id.equals(id) )).getSingle();
  }

  Future<List<Action>> fromActivity(Activity activity, Session session) async {
    final result = select(db.activityActions).join(
      [
        innerJoin(
          db.actions,
          db.actions.id.equalsExp(db.activityActions.actionId),
        ),
      ],
    )
      ..where(db.activityActions.activityId.equals(activity.id))
      ..where(db.activityActions.sessionId.equals(session.id));

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

    return actions;
  }

  Stream<List<Action>> watchActivityActions(Activity activity, Session session) {
    final result = select(db.activityActions).join(
      [
        innerJoin(
          db.actions,
          db.actions.id.equalsExp(db.activityActions.actionId),
        ),
      ],
    )
      ..where(db.activityActions.activityId.equals(activity.id))
      ..where(db.activityActions.sessionId.equals(session.id));

    // final actions = result.watch().map((rows) {
    //   return rows.map((row) {
    //     row.readTable(db.actions);
    //   }).toList();
    // });

    final actions = (result.watch()).map((rows) {
      return rows.map((row) => row.readTable(db.actions)).toList();
    });

    return actions;
  }

  Future createOrUpdate(ActionsCompanion action) => into(actions).insertOnConflictUpdate(action);
  Future replace(Action action) => update(actions).replace(action);
}
