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';
|
2021-08-03 22:02:42 +02:00
|
|
|
import 'package:jisho_study_tool/models/history/kanji_query.dart';
|
|
|
|
import 'package:jisho_study_tool/models/history/search.dart';
|
2021-07-17 16:11:17 +02:00
|
|
|
|
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> {
|
2021-07-17 16:11:17 +02:00
|
|
|
DatabaseBloc _databaseBloc;
|
|
|
|
|
|
|
|
KanjiBloc(this._databaseBloc) : super(KanjiSearch(KanjiSearchType.Initial));
|
|
|
|
|
2021-07-19 01:49:18 +02:00
|
|
|
void addSearchToDB(kanji) {
|
2021-07-17 16:11:17 +02:00
|
|
|
if (_databaseBloc.state is DatabaseDisconnected)
|
|
|
|
throw DatabaseNotConnectedException;
|
|
|
|
|
|
|
|
(_databaseBloc.state as DatabaseConnected)
|
2021-08-03 22:02:42 +02:00
|
|
|
.database
|
|
|
|
.box<Search>()
|
|
|
|
.put(Search(timestamp: DateTime.now())
|
|
|
|
..kanjiQuery.target = KanjiQuery(
|
|
|
|
kanji: kanji,
|
|
|
|
));
|
2021-07-17 16:11:17 +02:00
|
|
|
}
|
2020-07-09 20:06:48 +02:00
|
|
|
|
|
|
|
@override
|
2021-08-03 22:02:42 +02: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);
|
2021-08-03 22:02:42 +02:00
|
|
|
if (kanji.found)
|
|
|
|
yield KanjiSearchFinished(kanji: kanji);
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|