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 = [];
|
|
|
|
late final DelayedFunctionCaller _searchCaller;
|
|
|
|
final MovieManager manager;
|
|
|
|
bool searchingOnline = false;
|
|
|
|
|
|
|
|
LiveSearch(this.manager) {
|
2024-01-09 13:24:35 +01:00
|
|
|
_searchCaller = DelayedFunctionCaller(
|
|
|
|
searchOnline,
|
|
|
|
const Duration(milliseconds: 750),
|
|
|
|
resetTimerOnCall: true,
|
|
|
|
);
|
2024-01-08 21:48:13 +01:00
|
|
|
}
|
|
|
|
|
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;
|
2024-01-09 21:52:32 +01:00
|
|
|
List<MovieData> onlineResults = await manager.onlineSearch(searchTerm);
|
2024-01-08 21:48:13 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|