getTimesOfSession method

Future<List<TimeTraining>> getTimesOfSession(
  1. int? idSession, [
  2. String? comment,
  3. String? time,
  4. bool? dateAsc,
  5. bool? timeAsc,
])

Método para obtener los tiempos de una sesión específica con opción de búsqueda por comentario o tiempo.

Este método consulta la base de datos y devuelve una lista de todos los tiempos registrados para una sesión específica. Se puede filtrar la búsqueda por comentarios o por tiempo. También se puede ordenar los resultados por fecha o tiempo según los parámetros proporcionados.

Parámetros:

  • idSession: ID de la sesión de la que se desean obtener los tiempos.
  • comment (String?, opcional): Si se proporciona, la búsqueda filtrará los resultados que contengan este comentario en el campo comments.
  • time (String?, opcional): Si se proporciona, la búsqueda filtrará los resultados cuyos valores en timeInSeconds comiencen con este valor.
  • dateAsc (bool?, opcional): Si se proporciona, determina el orden de los resultados por fecha: true para ascendente, false para descendente.
  • timeAsc (bool?, opcional): Si se proporciona, determina el orden de los resultados por tiempo: true para ascendente, false para descendente.

Retorna:

  • Future<List<TimeTraining>>: Lista de objetos TimeTraining con los tiempos registrados que cumplen los criterios de búsqueda. Si no se encuentran resultados, devuelve una lista vacía.

Implementation

Future<List<TimeTraining>> getTimesOfSession(int? idSession,
    [String? comment, String? time, bool? dateAsc, bool? timeAsc]) async {
  try {
    if (idSession == null) {
      DatabaseHelper.logger.e("Error: idSession es nulo");
      return [];
    }

    // CONSTRUYE LA CONSULTA
    final query = supabase.from('timetraining').select();

    // APLICA FILTROS
    final filtered = query.eq('idsession', idSession);

    // VARIABLES A ALMACENAR LOS DAOTS
    dynamic result;

    // APLICAR FILTRO DE COMENTARIO SI EXISTE
    if (comment != null && comment.isNotEmpty) {
      if (time != null && time.isNotEmpty) {
        // SE OBTIENE TODOS LOS REGISTROS Y FILTRAMOS MANUALMENTE EL TIEMPO
        if (dateAsc != null) {
          result = await filtered
              .ilike('comments', '%$comment%')
              .order('registrationdate', ascending: dateAsc);
        } else if (timeAsc != null) {
          result = await filtered
              .ilike('comments', '%$comment%')
              .order('timeinseconds', ascending: timeAsc);
        } else {
          result = await filtered.ilike('comments', '%$comment%');
        }

        // FILTRAR MANUALMENTE POR EL TIEMPO DESPUES DE OBTENER LOS RESULTADOS
        if (result != null && result.isNotEmpty) {
          result = result
              .where((record) =>
                  record['timeinseconds'].toString().startsWith(time))
              .toList();
        }
      } else {
        // SOLO FILTRO DE COMENTARIOS SIN CAMBIOS
        if (dateAsc != null) {
          result = await filtered
              .ilike('comments', '%$comment%')
              .order('registrationdate', ascending: dateAsc);
        } else if (timeAsc != null) {
          result = await filtered
              .ilike('comments', '%$comment%')
              .order('timeinseconds', ascending: timeAsc);
        } else {
          result = await filtered.ilike('comments', '%$comment%');
        }
      }
    } else if (time != null && time.isNotEmpty) {
      // SOLO FILTRO DE TIEMPO, OBJEENMOS TODOS Y FILTRAMOS DESPUES
      if (dateAsc != null) {
        result = await filtered.order('registrationdate', ascending: dateAsc);
      } else if (timeAsc != null) {
        result = await filtered.order('timeinseconds', ascending: timeAsc);
      } else {
        result = await filtered;
      }

      // FILTRAR MANUALMENTE POR TIEMPO
      if (result != null && result.isNotEmpty) {
        result = result
            .where((record) =>
                record['timeinseconds'].toString().startsWith(time))
            .toList();
      }
    } else {
      // SIN FILTROS, SOLO ORDENACION SIN CAMBIOS
      if (dateAsc != null) {
        result = await filtered.order('registrationdate', ascending: dateAsc);
      } else if (timeAsc != null) {
        result = await filtered.order('timeinseconds', ascending: timeAsc);
      } else {
        result = await filtered; // SIN ORDENACION
      }
    }

    // CONVERTIR LOS RESULTADOS A OBJETOS
    if (result != null && result.isNotEmpty) {
      return result.map<TimeTraining>((map) {
        return TimeTraining(
          idTimeTraining: map['idtimetraining'] as int,
          idSession: map['idsession'] as int,
          scramble: map['scramble'] as String,
          timeInSeconds: (map['timeinseconds'] as num).toDouble(),
          comments: map['comments'] as String?,
          penalty: map['penalty'] as String,
          registrationDate: map['registrationdate'] as String,
        );
      }).toList();
    } else {
      return [];
    }
  } catch (e) {
    DatabaseHelper.logger.e("Error al obtener los tiempos de la sesion: $e");
    return [];
  }
}