import 'dart:async'; import 'dart:math'; import '/features/core/data/constants/const_values.dart'; import '/features/core/data/extensions/random_extensions.dart'; import '/l10n/generated/l10n.dart'; import '/locator.dart'; import '../abstracts/images_api.dart'; import '../data/dtos/image_model_dto.dart'; class UnsplashImagesApi extends ImagesApi { UnsplashImagesApi({required super.token}); //final LoggingService _loggingService = LoggingService.locate; final random = Random(); @override FutureOr> fetchImageUri() async { // Dummy fetching delay emulation await Future.delayed( const Duration( milliseconds: ConstValues.defaultEmulatedLatencyMillis * ConstValues.numberOfImages, ), ); final Iterable> fetchedImageModelDtos; try { // Create fixed number of images final dummyImageModels = Iterable.generate(ConstValues.numberOfImages).map((final imageIndex) { // Drawing from a normal distribution final imageSide = random.nextIntInRange(min: ConstValues.minImageSize, max: ConstValues.maxImageSize); final imageUri = _imageUrlGenerator(imageSide: imageSide); return ImageModelDTO( imageIndex: imageIndex, uri: imageUri, // Custom dummy name for the image imageName: Strings.current.imageNameFetch(imageIndex + 1, imageSide), ); }); // Emulating serialization fetchedImageModelDtos = dummyImageModels.map((final dummyModel) => dummyModel.toJson()); } on Exception catch (ex, stackTrace) { loggingService.handleException(ex, stackTrace); return const Iterable.empty(); } // Emulating deserialization return fetchedImageModelDtos.map(ImageModelDTO.fromJson); } @override FutureOr> searchImages({ required String searchStr, }) async { final numberOfResults = random.nextIntInRange(min: 0, max: ConstValues.numberOfImages); // Dummy fetching delay emulation await Future.delayed( Duration( milliseconds: ConstValues.defaultEmulatedLatencyMillis * numberOfResults, ), ); final Iterable> searchImageModelDtos; try { // Create (randomly-bounded) dummy number of images final dummyImageModels = Iterable.generate(numberOfResults).map((final imageIndex) { // Drawing from a normal distribution final imageSide = random.nextIntInRange(min: ConstValues.minImageSize, max: ConstValues.maxImageSize); final imageUri = _imageUrlGenerator(imageSide: imageSide); return ImageModelDTO( imageIndex: imageIndex, uri: imageUri, // Custom dummy name for the image imageName: Strings.current.imageNameSearch(searchStr, imageIndex + 1), ); }); // Emulating serialization searchImageModelDtos = dummyImageModels.map((final dummyModel) => dummyModel.toJson()); } on Exception catch (ex, stackTrace) { loggingService.handleException(ex, stackTrace); return List.empty(); } return searchImageModelDtos.map(ImageModelDTO.fromJson); } Uri _imageUrlGenerator({required int imageSide}) => Uri( scheme: ConstValues.httpsScheme, host: ConstValues.imagesHostServer, pathSegments: [...ConstValues.imagesHostUrlPathSegments, '${imageSide}x$imageSide'], ); static UnsplashImagesApi get locate => Locator.locate(); }