import 'dart:math';

import 'package:camera/camera.dart';
import '../data/session/session_storage.dart';
import '../services/services.dart';
import 'package:http/http.dart' as http;

class GeneralService extends BaseService {
  Map<String, String> defaultQueryParameters = {"ordenar": "id-desc"};

  Future<http.StreamedResponse> enviarMedia(
      {required int id,
      required XFile media,
      String? modulo,
      String? tipo,
      String? etiquetaID}) async {
    //ejemplo: tipo = imagen, modulo = Visita
    final token = await SessionStorage().getToken();
    String completo = "$base_url/admin/media/guardar";
    String nombre = "generico";
    http.MultipartRequest request =
        http.MultipartRequest('POST', Uri.parse(completo));
    request.headers.addAll({
      'Content-type': 'multipart/form-data',
      'Accept': 'application/json',
      'Authorization': "Bearer $token"
    });
    if (tipo == "archivo") {
      final random = Random();
      final randomInt = random.nextInt(99999);
      int lastIndex = media.name.lastIndexOf('.');
      nombre = "$randomInt";
      if (lastIndex != -1 && lastIndex < media.name.length - 1) {
        String ext = media.name.substring(lastIndex + 1);
        nombre = "$nombre.${ext.toLowerCase()}";
      }
      nombre = media.name.toString();
    }
    if (tipo == "imagen") {
      final random = Random();
      final randomInt = random.nextInt(99999);
      nombre = "$randomInt.jpg";
    }
    if (tipo == "audio") {
      final random = Random();
      final randomInt = random.nextInt(99999);
      nombre = "$randomInt.wav";
    }
    request.fields[etiquetaID.toString()] = "$id";
    request.fields[modulo.toString()] = '1';
    request.fields['tipo'] = tipo.toString();
    request.files.add(
      http.MultipartFile(
        'archivo',
        media.openRead(),
        await media.length(),
        filename: nombre,
      ),
    );

    return await request.send();
  }
}
