import 'dart:convert';

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

import '../../../common/constant/local_storage_key.dart';
import '../../../domain/outlet/outlet.dart';
import '../outlet_dtos.dart';

@injectable
class OutletLocalDatasource {
  final SharedPreferences _sharedPreferences;
  // final String _logName = 'OutletLocalDataProvider';

  OutletLocalDatasource(this._sharedPreferences);

  Future<void> saveCurrentOutlet(OutletDto outlet) async {
    final outletJsonString = jsonEncode(outlet.toJson());
    await _sharedPreferences.setString(
      LocalStorageKey.outlet,
      outletJsonString,
    );
  }

  Future<Outlet> currentOutlet() async {
    final outletString = _sharedPreferences.getString(LocalStorageKey.outlet);
    if (outletString == null) return Outlet.empty();

    final Map<String, dynamic> outletMap = jsonDecode(outletString);
    final outletDto = OutletDto.fromJson(outletMap);
    return outletDto.toDomain();
  }

  Future<void> deleteCurrentOutlet() async {
    await _sharedPreferences.remove(LocalStorageKey.outlet);
  }
}
