import '../../globals.dart';
import '../../models/hashtag.dart';
import '../../objectbox.g.dart';
import '../interfaces/hashtag_repo_intf.dart';
import 'objectbox_cache.dart';

class ObjectBoxHashtagRepo implements IHashtagRepo {
  late final Box<Hashtag> box;

  ObjectBoxHashtagRepo() {
    box = getIt<ObjectBoxCache>().store.box<Hashtag>();
  }

  @override
  Future<void> clear() async {
    await box.removeAllAsync();
  }

  @override
  void add(Hashtag tag) {
    box.putQueued(tag);
  }

  @override
  List<String> getMatchingHashTags(String text) {
    return (box
            .query(
              text.length <= 2
                  ? Hashtag_.tag.startsWith(text, caseSensitive: false)
                  : Hashtag_.tag.contains(text, caseSensitive: false),
            )
            .order(Hashtag_.tag)
            .build()
          ..limit = 100)
        .find()
        .map((h) => h.tag)
        .toList();
  }
}
