import 'dart:io';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:taafee_mobile/core/local_storage/local_storage.dart';
import 'package:path_provider/path_provider.dart';

class ChatFilesSource {
  final Dio _dio = Dio(BaseOptions(
    baseUrl: 'https://pages-chat-dev.octa-apps.com/',
    headers: {
      "Authorization": LocalStorage().getChatToken(),
    },
  ));

  Future<int> uploadFile(
      {required int roomId, required String filePath}) async {
    Map<String, dynamic> body = {
      "file": MultipartFile.fromFileSync(filePath),
      "roomId": roomId,
    };
    var response = await _dio.post('room/file',
        data: FormData.fromMap(body),
        options: Options(
          headers: {
            "Authorization": LocalStorage().getChatToken(),
          },
        ));
    return response.data['response'];
  }

  Future<File> getVoiceFile(String id) async {
    Response response = await _dio.get('/room/file/$id',
        options: Options(
          responseType: ResponseType.bytes,
          headers: {
            "Authorization": LocalStorage().getChatToken(),
          },
        ));
    var dir = await getTemporaryDirectory();
    int random = Random(5).nextInt(10000);
    var file = File('${dir.path}/audio$random.m4a');
    await file.writeAsBytes(response.data);
    return file;
  }
}
