import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';

class ConfigService {
  static const String _localeKey = 'locale';
  static const String _hdThumbnailsKey = 'hd_thumbnails';
  static const String _pdfDownloadKey = 'pdf_download';
  static const String _lastDateKey = 'last_date';

  static Future<String> getLocale() async {
    final prefs = await SharedPreferences.getInstance();
    final deviceLocale = Platform.localeName.split('_')[0];
    return prefs.getString(_localeKey) ?? deviceLocale;
  }

  static Future<void> setLocale(String locale) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_localeKey, locale);
  }

  static Future<bool> getHdThumbnails() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_hdThumbnailsKey) ?? true;
  }

  static Future<void> setHdThumbnails(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_hdThumbnailsKey, value);
  }

  static Future<bool> getPdfDownload() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_pdfDownloadKey) ?? true;
  }

  static Future<void> setPdfDownload(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_pdfDownloadKey, value);
  }

  static Future<String> getLastDate(String locale) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString('$_lastDateKey-$locale') ?? '0';
  }

  static Future<void> setLastDate(String locale, String date) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('$_lastDateKey-$locale', date);
  }

  static Future<void> initializeConfig() async {
    final prefs = await SharedPreferences.getInstance();

    // Initialize default values if they don't exist
    if (!prefs.containsKey(_hdThumbnailsKey)) {
      await setHdThumbnails(true);
    }
    if (!prefs.containsKey(_pdfDownloadKey)) {
      await setPdfDownload(true);
    }
    if (!prefs.containsKey(_localeKey)) {
      await setLocale(Platform.localeName.split('_')[0]);
    }
  }
}
