2024-01-08 21:48:13 +01:00
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:release_schedule/model/delayed_function_caller.dart';
|
|
|
|
import 'package:release_schedule/model/movie.dart';
|
|
|
|
import 'package:release_schedule/model/movie_manager.dart';
|
|
|
|
|
|
|
|
class LiveSearch extends ChangeNotifier {
|
|
|
|
String searchTerm = "";
|
|
|
|
List<MovieData> searchResults = [];
|
|
|
|
Duration minTimeBetweenRequests = const Duration(milliseconds: 200);
|
|
|
|
late final DelayedFunctionCaller _searchCaller;
|
|
|
|
final MovieManager manager;
|
|
|
|
bool searchingOnline = false;
|
|
|
|
|
|
|
|
LiveSearch(this.manager) {
|
|
|
|
_searchCaller = DelayedFunctionCaller(searchOnline, minTimeBetweenRequests);
|
|
|
|
}
|
|
|
|
|
2024-01-09 12:47:42 +01:00
|
|
|
get loading => searchingOnline || _searchCaller.scheduled;
|
|
|
|
|
2024-01-08 21:48:13 +01:00
|
|
|
void updateSearch(String search) {
|
|
|
|
searchTerm = search;
|
|
|
|
if (searchTerm.isEmpty) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
searchResults = manager.localSearch(search);
|
|
|
|
_searchCaller.call();
|
|
|
|
notifyListeners();
|
|
|
|
}
|
|
|
|
|
|
|
|
void searchOnline() async {
|
|
|
|
if (searchTerm.isEmpty) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (searchingOnline) {
|
|
|
|
_searchCaller.call();
|
2024-01-08 21:58:18 +01:00
|
|
|
notifyListeners();
|
2024-01-08 21:48:13 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
searchingOnline = true;
|
|
|
|
try {
|
|
|
|
String startedSearching = searchTerm;
|
|
|
|
List<MovieData> onlineResults =
|
|
|
|
await movieManager.onlineSearch(searchTerm);
|
|
|
|
searchingOnline = false;
|
|
|
|
// if the search term has changed since we started searching, ignore the results
|
|
|
|
if (startedSearching != searchTerm) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
List<MovieData> localResults = manager.localSearch(searchTerm);
|
|
|
|
localResults.removeWhere((element) => onlineResults.contains(element));
|
|
|
|
searchResults = onlineResults + localResults;
|
|
|
|
notifyListeners();
|
|
|
|
} finally {
|
|
|
|
searchingOnline = false;
|
2024-01-08 21:58:18 +01:00
|
|
|
notifyListeners();
|
2024-01-08 21:48:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|