import 'dart:convert';

import 'package:cargocalculaterapp/features/profile/data/data_source/local/profile_local_data_source.dart';
import 'package:cargocalculaterapp/features/profile/data/models/profile_response.dart';
import 'package:hive/hive.dart';
import '../../../../../constants/constants.dart';
import '../../../../../core/error/exceptions.dart';

class ProfileLocalDataSourceImpl extends ProfileLocalDataSource {
  final Box<dynamic> box;

  ProfileLocalDataSourceImpl(this.box);

  @override
  Future<ProfileResponse> getProfile() async {
    final json = await box.get(CacheKeys.profile, defaultValue: null);
    if (json != null) {
      return ProfileResponse.fromJson(jsonDecode(json));
    } else {
      throw CacheException(message: Validations.someThingWentWrong);
    }
  }

  @override
  Future<void> setProfile(ProfileResponse response) async {
    final json = jsonEncode(response.toJson());
    await box.put(CacheKeys.profile, json);
  }
}
