import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sendtrain/daos/activities_dao.dart';
import 'package:sendtrain/database/database.dart';
import 'package:sendtrain/helpers/widget_helpers.dart';
import 'package:sendtrain/widgets/generic/elements/form_search_input.dart';

class ActivityFinderService {
  final BuildContext context;
  final ActivitiesDao dao;

  ActivityFinderService(this.context)
      : dao = ActivitiesDao(Provider.of<AppDatabase>(context, listen: false));

  void finish() {}

  Future<List<Suggestion>?> fetchSuggestions(String input) async {
    List<Activity> activities = await dao.contains(input);

    if (activities.isNotEmpty) {
      return activities
          .map<Suggestion>((activity) => Suggestion<Activity>(activity))
          .toList();
    } else {
      return null;
    }
  }

  Widget resultWidget(Activity activity, Function? callback) {
    return ListTile(
      title: Text(activity.title),
      subtitle: Text(jsonToDescription(json.decode(activity.description ?? "")),
          maxLines: 2, softWrap: true, overflow: TextOverflow.ellipsis),
      onTap: () {
        if (callback != null) {
          callback();
        }
      },
    );
  }
}
