import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart' show ByteData, rootBundle;
import 'package:uuid/uuid.dart';

class SharedPreferencesProvider extends ChangeNotifier {
  late SharedPreferences prefs;
  final Completer<void> _initCompleter = Completer<void>();

  SharedPreferencesProvider() {
    _initPrefs();
  }

  Future<void> _initPrefs() async {
    prefs = await SharedPreferences.getInstance();
    if (prefs.getString('userLogo') == null) {
      ByteData bytes =
          await rootBundle.load('assets/default_profile_image.png');
      List<int> imageBytes = bytes.buffer.asUint8List();
      prefs.setString('userLogo', base64Encode(imageBytes));
      prefs.setString('id', const Uuid().v4());
      prefs.setString('currentStatus', 'none');
    }
    _initCompleter.complete();
    notifyListeners();
  }

  Future<void> get ready => _initCompleter.future;

  String getUserName() {
    return prefs.getString('userName') ?? '';
  }

  Future<void> setUserName(String name) async {
    await prefs.setString('userName', name);
    notifyListeners();
  }

  String getUserId() {
    return prefs.getString('id') ?? '';
  }

  String? getUserLogo() {
    final userLogo = prefs.getString('userLogo');
    return userLogo;
  }

  Future<void> setUserLogo(String? image) async {
    await prefs.setString('userLogo', image!);
    notifyListeners();
  }

  // New methods to get and set the current status
  String getCurrentStatus() {
    return prefs.getString('currentStatus') ?? 'none';
  }

  Future<void> setCurrentStatus(String status) async {
    await prefs.setString('currentStatus', status);
    notifyListeners();
  }
}
