// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:architecture_example/core/constants/hive_boxes.dart';
import 'package:architecture_example/domain/data_sources/local/favorite_local_data_source.dart';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:hive/hive.dart';

class FavoriteHiveDataSource extends FavoriteLocalDataSource {
  @override
  Future<void> addPhotoToFavorites(Photo photo) async {
    final box = await Hive.openBox<bool>(HiveBoxes.favorites);
    if (box.containsKey(photo.id)) {
      throw Exception('Photo already in favorites');
    }
    await box.put(photo.id, true);
  }

  @override
  Future<bool> checkIfPhotoIsInFavorites(int id) async {
    final box = await Hive.openBox<bool>(HiveBoxes.favorites);
    return box.containsKey(id);
  }

  @override
  Future<void> deletePhotoFromFavorites(int id) async {
    final box = await Hive.openBox<bool>(HiveBoxes.favorites);
    if (!box.containsKey(id)) {
      throw Exception('Unknown photo');
    }
    await box.delete(id);
  }

  @override
  Future<List<int>> getAllPhotosFromFavorites() async {
    final box = await Hive.openBox<bool>(HiveBoxes.favorites);
    return box.keys.cast<int>().toList();
  }
}
