import 'dart:async';

import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

class PDFCommonFunctions {
  //-------------------image-------------------------
  Future<dynamic> getNetworkImage(String imageURL) async {
    if (imageURL.isEmpty) return null;

    try {
      final Uri uri = Uri.parse(imageURL);
      final response = await http.get(uri);

      if (response.statusCode != 200) {
        print('Failed to load image: ${response.statusCode}');
        return null;
      }

      final contentType = response.headers['content-type']?.toLowerCase() ?? '';

      // SVG support
      if (contentType.contains('svg')) {
        return response.body;
      }

      // Fallback: if it's application/octet-stream or empty, assume it's a binary image
      if (contentType.contains('image/') || contentType == 'application/octet-stream' || contentType.isEmpty) {
        return Uint8List.fromList(response.bodyBytes);
      }

      print('Unsupported image type from Content-Type: $contentType');
      return null;
    } catch (e) {
      print('Error loading image: $e');
      return null;
    }
  }

  // Future<dynamic> getNetworkImage(String imageURL) async {
  //   if (imageURL.isEmpty) return null;
  //   try {
  //     final Uri uri = Uri.parse(imageURL);
  //     final String fileExtension = uri.path.split('.').last.toLowerCase();
  //     if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
  //       final List<int> responseBytes = await http.readBytes(uri);
  //       return Uint8List.fromList(responseBytes);
  //     } else if (fileExtension == 'svg') {
  //       final response = await http.get(uri);
  //       return response.body;
  //     } else {
  //       print('Unsupported image type: $fileExtension');
  //       return null;
  //     }
  //   } catch (e) {
  //     print('Error loading image: $e');
  //     return null;
  //   }
  // }

  Future<Uint8List?> loadAssetImage(String path) async {
    try {
      final ByteData data = await rootBundle.load(path);
      return data.buffer.asUint8List();
    } catch (e) {
      print('Error loading local image: $e');
      return null;
    }
  }
}
