2020-07-09 20:06:48 +02:00
|
|
|
import 'dart:async';
|
|
|
|
|
2021-07-17 16:11:17 +02:00
|
|
|
import 'package:jisho_study_tool/bloc/database/database_bloc.dart';
|
|
|
|
import 'package:jisho_study_tool/models/history/search.dart';
|
|
|
|
|
2020-07-13 15:18:17 +02:00
|
|
|
import './kanji_event.dart';
|
|
|
|
import './kanji_state.dart';
|
2020-07-09 20:06:48 +02:00
|
|
|
|
2020-07-13 15:18:17 +02:00
|
|
|
import 'package:bloc/bloc.dart';
|
2021-03-02 22:26:59 +01:00
|
|
|
import 'package:jisho_study_tool/services/jisho_api/kanji_search.dart';
|
2020-07-21 23:29:02 +02:00
|
|
|
import 'package:jisho_study_tool/services/kanji_suggestions.dart';
|
2020-07-09 20:06:48 +02:00
|
|
|
|
2020-07-13 21:21:33 +02:00
|
|
|
export './kanji_event.dart';
|
|
|
|
export './kanji_state.dart';
|
|
|
|
|
2020-07-09 20:06:48 +02:00
|
|
|
class KanjiBloc extends Bloc<KanjiEvent, KanjiState> {
|
2020-07-13 15:18:17 +02:00
|
|
|
|
2021-07-17 16:11:17 +02:00
|
|
|
DatabaseBloc _databaseBloc;
|
|
|
|
|
|
|
|
KanjiBloc(this._databaseBloc) : super(KanjiSearch(KanjiSearchType.Initial));
|
|
|
|
|
|
|
|
void addSearchToDB(searchString) {
|
|
|
|
if (_databaseBloc.state is DatabaseDisconnected)
|
|
|
|
throw DatabaseNotConnectedException;
|
|
|
|
|
|
|
|
(_databaseBloc.state as DatabaseConnected)
|
|
|
|
.database
|
|
|
|
.box<Search>()
|
|
|
|
.put(Search(
|
|
|
|
query: searchString,
|
|
|
|
timestamp: DateTime.now(),
|
|
|
|
type: "kanji"
|
|
|
|
));
|
|
|
|
}
|
2020-07-09 20:06:48 +02:00
|
|
|
|
|
|
|
@override
|
2021-03-02 22:26:59 +01:00
|
|
|
Stream<KanjiState> mapEventToState(KanjiEvent event)
|
|
|
|
async* {
|
2020-07-13 15:18:17 +02:00
|
|
|
if (event is GetKanji) {
|
2020-07-14 00:09:54 +02:00
|
|
|
|
|
|
|
yield KanjiSearchLoading();
|
|
|
|
|
2020-07-13 15:18:17 +02:00
|
|
|
try {
|
2021-07-17 16:11:17 +02:00
|
|
|
addSearchToDB(event.kanjiSearchString);
|
2021-03-03 00:24:25 +01:00
|
|
|
final kanji = await fetchKanji(event.kanjiSearchString);
|
|
|
|
if (kanji.found) yield KanjiSearchFinished(kanji: kanji);
|
2020-07-16 14:08:35 +02:00
|
|
|
else yield KanjiSearchError('Something went wrong');
|
2020-07-13 15:18:17 +02:00
|
|
|
} on Exception {
|
|
|
|
yield KanjiSearchError('Something went wrong');
|
|
|
|
}
|
2020-07-21 23:29:02 +02:00
|
|
|
} else if (event is GetKanjiSuggestions) {
|
|
|
|
|
|
|
|
final suggestions = kanjiSuggestions(event.searchString);
|
2021-07-17 12:19:03 +02:00
|
|
|
yield KanjiSearchKeyboard(KanjiSearchType.Keyboard, suggestions);
|
2020-07-14 00:09:54 +02:00
|
|
|
|
|
|
|
} else if (event is ReturnToInitialState) {
|
2021-07-17 12:19:03 +02:00
|
|
|
yield KanjiSearch(KanjiSearchType.Initial);
|
2020-07-13 15:18:17 +02:00
|
|
|
}
|
2020-07-09 20:06:48 +02:00
|
|
|
}
|
|
|
|
}
|