import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';

import 'package:share_plus/share_plus.dart';

import 'package:pshared/service/authorization/service.dart';
import 'package:pshared/utils/image/conversion.dart';
import 'package:pshared/utils/image/transformed.dart';


String generateRandomLatinString(int length) {
  const String chars = 'abcdefghijklmnopqrstuvwxyz';
  final Random random = Random.secure();
  return List.generate(length, (index) => chars[random.nextInt(chars.length)]).join();
}

class FilesService {
  static Future<String> uploadImage(
    String objectType,
    String? id,
    XFile imageFile, {
    Future<TransformedImage> Function(XFile) fileReader = defaultTransformImage,
  }) async {
    final objRef = id ?? generateRandomLatinString(16);
    final image = await fileReader(imageFile);
    final res = await AuthorizationService.getFileUploadResponseAuth(
      objectType, 
      'image/$objRef',
      '$objRef.${image.imageType.split('/').last}', 
      'image', 
      image.imageType, 
      image.bytes
    );
    CachedNetworkImage.evictFromCache(res);
    return res;
  }
}
