import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:file_picker/file_picker.dart';

// Guarda la imagen que se añade desde el form
Future<String?> pickAndStoreImage(File file, int productId) async {
  Directory appDocDir = await getApplicationDocumentsDirectory();
  String baseDirPath =
      path.join(appDocDir.path, 'TurquessaPos', 'media', 'producto');
  await Directory(baseDirPath).create(recursive: true);
  String fileExtension = path.extension(file.path);
  String newFileName =
      "$productId-${path.basenameWithoutExtension(file.path)}$fileExtension";
  String finalPath = path.join(baseDirPath, newFileName);

  await file.copy(finalPath);

  return finalPath;
}

//Descarga imagen de la sincronizacion del producto
Future<String?> downloadAndStoreImage(
    String imageUrl, int productId, String imageName) async {
  Directory appDocDir = await getApplicationDocumentsDirectory();
  String baseDirPath =
      path.join(appDocDir.path, 'TurquessaPos', 'media', 'producto');
  await Directory(baseDirPath).create(recursive: true);

  String fileExtension = path.extension(imageUrl);
  String newFileName = "$productId-$imageName$fileExtension";
  String finalPath = path.join(baseDirPath, newFileName);

  http.Response response = await http.get(Uri.parse(imageUrl));
  if (response.statusCode == 200) {
    Uint8List bytes = response.bodyBytes;
    File file = File(finalPath);
    await file.writeAsBytes(bytes);
    return finalPath;
  }

  return null;
}
