import 'package:anyway/structs/trip.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:flutter/foundation.dart';

class SavedTrips extends ChangeNotifier {
  List<Trip> _trips = [];

  List<Trip> get trips => _trips;

  void loadTrips() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    List<Trip> trips = [];
    Set<String> keys = prefs.getKeys();
    for (String key in keys) {
      if (key.startsWith('trip_')) {
        String uuid = key.replaceFirst('trip_', '');
        trips.add(Trip.fromPrefs(prefs, uuid));
      }
    }
    _trips = trips;
    notifyListeners();
  }

  void addTrip(Trip trip) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    trip.toPrefs(prefs);
    _trips.add(trip);
    notifyListeners();
  }

  void clearTrips () async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
    _trips = [];
    notifyListeners();
  }
}