import 'package:image/image.dart' as img;

import 'package:share_plus/share_plus.dart';

import 'package:pshared/api/errors/failed_to_read_image.dart';
import 'package:pshared/config/constants.dart';
import 'package:pshared/utils/image/transformed.dart';


bool _imageTooBig(img.Image image, int maxDimension) {
  return image.width > maxDimension && image.height > maxDimension;
}

bool _imageTooSmall(img.Image image, int maxDimension) {
  return image.width < maxDimension && image.height < maxDimension;
}

TransformedImage _getImageBytes(img.Image image, int maxDimension) {
  List<int> imageBytes;

  if (_imageTooBig(image, maxDimension) || _imageTooSmall(image, maxDimension)) {
    final double scale = image.width < image.height
        ? maxDimension / image.width
        : maxDimension / image.height;
    
    int newWidth = (image.width * scale).toInt();
    int newHeight = (image.height * scale).toInt();

    final img.Image resizedImage = img.copyResize(image, width: newWidth, height: newHeight);
    image = resizedImage;
  }

  imageBytes = img.encodePng(image);
  return TransformedImage(imageBytes, 'image/png');
}

Future<TransformedImage> defaultTransformImage(XFile file, {int? maxDimension}) async {
  maxDimension = maxDimension ?? Constants.defaultDimensionLength;
  img.Image? image = img.decodeImage(await file.readAsBytes());
  if (image == null) {
    throw ErrorFailedToReadImage();
  }

  return _getImageBytes(image, maxDimension);
}
