import 'dart:io';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

class ImageService {
  static Future<String?> saveImageToLocalDirectory(
    File sourceFile,
    String dir,
  ) async {
    try {
      final directory = await getApplicationDocumentsDirectory();

      final String path = directory.path;
      final Directory imageDir = Directory('$path/$dir');
      if (!await imageDir.exists()) {
        await imageDir.create(recursive: true);
      }

      final String fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg';

      final String newPath = p.join(imageDir.path, fileName);

      final File newImage = await sourceFile.copy(newPath);

      return newImage.path;
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      return null;
    }
  }

  static Future<void> deleteLocalImage(String path) async {
    try {
      final file = File(path);
      if (await file.exists()) {
        await file.delete();
      }
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
    }
  }
}
