import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:road24_mobile/data/http/ApiRequest.dart';

class UploadFileRepository {
  static ValueNotifier<Map<String, double>> currentlyUploadingFiles =
      ValueNotifier({});

  Future<dynamic> uploadFile(String filePath, String fileName) async {
    var res = await uploadImage(filePath, fileName);

    return res;
  }

  Future<dynamic> uploadFilesToServer({
    required String fileName,
    required String filePath,
    String? module,
  }) async {
    UploadFileRepository.currentlyUploadingFiles.value.addAll({fileName: 0.0});
    dynamic response = await doUploadRequest(
      "files/",
      data: module == null
          ? await formDataNew(filePath, fileName)
          : await formDataNewForReport(
              filePath,
              fileName,
              module,
            ),
      onSendProgress: (received, total) {
        if (total != -1) {
          UploadFileRepository.currentlyUploadingFiles.value[fileName] =
              received * 100 / total;
          // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
          UploadFileRepository.currentlyUploadingFiles.notifyListeners();
        }
      },
    );

    return response;
  }

  Future<FormData> formDataNew(String filePath, String fileName) async {
    return FormData.fromMap({
      "name": fileName,
      "file": await MultipartFile.fromFile(
        filePath,
        filename: fileName,
      ),
      "content": "Nothing",
    });
  }

  Future<FormData> formDataNewForReport(
      String filePath, String fileName, String module) async {
    return FormData.fromMap({
      "name": fileName,
      "file": await MultipartFile.fromFile(
        filePath,
        filename: fileName,
      ),
      "module": module,
      "content": "Nothing",
    });
  }
}
