import 'dart:io';

import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image/image.dart' as resizeImage;
import 'package:path_provider/path_provider.dart' as path_provider;

Future<List<int>> getImageDimensions(String imagePath) async {
  final bytes = await File(imagePath).readAsBytes();
  final image = resizeImage.decodeImage(bytes);

  if (image != null) {
    final width = image.width;
    final height = image.height;

    print('Width: $width');
    print('Height: $height');
  } else {
    print('Failed to decode image');
  }
  return [image!.width, image.height];
}

Future<String> compressFoto(String path, bool absensi, bool landscape) async {
  final dir = await path_provider.getTemporaryDirectory();
  File fileCompressed = File(path);
  resizeImage.Image? imageNew =
      resizeImage.decodeImage(fileCompressed.readAsBytesSync());
  resizeImage.Image? thumbnail;
  // resizeImage.Image? thumbnail = resizeImage.copyResize(imageNew!, height: absensi==true?800:400);
  if (landscape) {
    thumbnail =
        resizeImage.copyResize(imageNew!, height: absensi == true ? 500 : 500);
  } else {
    thumbnail =
        resizeImage.copyResize(imageNew!, width: absensi == true ? 500 : 500);
  }
  fileCompressed = new File(path)
    ..writeAsBytesSync(resizeImage.encodePng(thumbnail));
  fileCompressed = await testCompressAndGetFile(
      File(path), "${dir.absolute.path}/${DateTime.now()}.jpg");
  print("fileCompressed ${fileCompressed.path}");
  return fileCompressed.path;
}

Future<File> testCompressAndGetFile(File file, String targetPath) async {
  final result = await FlutterImageCompress.compressAndGetFile(
    file.absolute.path,
    targetPath,
    quality: 75,
  );

  if (result == null) {
    throw Exception('Compression failed');
  }

  print(file.lengthSync());

  // Convert XFile to File
  return File(result.path);
}
