import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:anyway/domain/entities/preferences.dart';
import 'package:anyway/domain/repositories/preferences_repository.dart';

class PreferencesRepositoryImpl implements PreferencesRepository {
  static const _key = 'userPreferences';

  @override
  Future<Preferences> getPreferences() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_key);
    if (raw == null) {
      // TODO - rethink this
      // return a sensible default
      return Preferences(
        scores: {
          'sightseeing': 0,
          'shopping': 0,
          'nature': 0,
        },
        maxTimeMinutes: 120,
        startLocation: const [48.8575, 2.3514],
      );
    }

    try {
      final map = json.decode(raw) as Map<String, dynamic>;
      return Preferences.fromJson(map);
    } catch (_) {
      return Preferences(
        scores: {
          'sightseeing': 0,
          'shopping': 0,
          'nature': 0,
        },
        maxTimeMinutes: 120,
        startLocation: const [48.8575, 2.3514],
      );
    }
  }

  @override
  Future<void> savePreferences(Preferences preferences) async {
    final prefs = await SharedPreferences.getInstance();
    final raw = json.encode(preferences.toJson());
    await prefs.setString(_key, raw);
  }
}
