import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'package:flutter/material.dart';
import '../Testk_Repo/Testk_repo_screen.dart';

class TestkViewModelScreen extends ChangeNotifier{
  final TestkRepoScreen repo = TestkRepoScreen();

  Future<List<Map<String, dynamic>>> getEntities() async {
    try {
      final response = await repo.getEntities();
      final entities = (response as List).cast<Map<String, dynamic>>();
      return entities;
    } catch (e) {
      throw Exception('Failed to get all entities: $e');
    }
  }

  
  Future<List<Map<String, dynamic>>> getAllWithPagination(
      int page, int size) async {
    try {
      final response =
          await repo.getAllWithPagination(page, size); // ✅ Use await

      print('res - $response');

      // ✅ Ensure response is a Map<String, dynamic>
      if (response is! Map<String, dynamic>) {
        throw Exception('Unexpected response format: $response');
      }

      // ✅ Extract 'content' and ensure it's a list
      final entities = (response['content'] as List)
          .cast<Map<String, dynamic>>() // ✅ Ensure list of maps
          .toList();
      return entities;
    } catch (e) {
      print(e);
      throw Exception('Failed to get all without pagination :- $e');
    }
  }

  
  Future<Map<String, dynamic>> createEntity(Map<String, dynamic> entity) async {
    try {
      print("in post api - $entity");
      // Wait for API response
      final responseData =
          await repo.createEntity(entity) as Map<String, dynamic>;
      print('after value - $responseData');
      ToastMessageUtil.showToast(
          message: "Added Successfully", toastType: ToastType.success);

      return responseData; // Return the data AFTER it is received
    } catch (error) {
      print("error--$error");
      ToastMessageUtil.showToast(
          message: "Got Error", toastType: ToastType.error);

      throw Exception(
          'Failed to Create Entity: $error'); // Properly rethrow the error
    }
  } 
  Future<void> updateEntity(int entityId, Map<String, dynamic> entity) async {
    try {
      repo.updateEntity(entityId, entity).then((value) {
        ToastMessageUtil.showToast(
            message: "Updated Successfully", toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Got Error", toastType: ToastType.error);
        },
      );
      print(entity);
    } catch (e) {
      throw Exception('Failed to update entity: $e');
    }
  }

  Future<void> deleteEntity(int entityId) async {
    try {
      repo.deleteEntity(entityId).then((value) {
        ToastMessageUtil.showToast(
            message: "Deleted Successfully", toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Got Error", toastType: ToastType.error);
        },
      );
    } catch (e) {
      throw Exception('Failed to delete entity: $e');
    }
  }













// Modify the uploadfileuploadximage function
  Future<void> uploadfileuploadx(String ref, String refTableNmae,
      String selectedFilePath, Uint8List imageTimageBytes) async {
    try {

      final Uint8List fileBytes = imageTimageBytes!;
      final mimeType = fileuploadxlookupMimeType(selectedFilePath);

      FormData formData = FormData.fromMap({
        'file': MultipartFile.fromBytes(
          fileBytes,
          filename: selectedFilePath
              .split('/')
              .last, // Get the file name from the path
          contentType: MediaType.parse(mimeType!),
        ),
      });


      await repo.fileuploadxUpload(ref, refTableNmae, formData).then((value) {
        ToastMessageUtil.showToast(
            message: "File uploaded successfully",
            toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Failed to upload file", toastType: ToastType.error);
        },
      );
    } catch (error) {
      print('Error occurred during form submission: $error');
    }
  }

// Modify the lookupMimeType function if needed
  String fileuploadxlookupMimeType(String filePath) {
    final ext = filePath.split('.').last;
    switch (ext) {
      case 'jpg':
      case 'jpeg':
        return 'image/jpeg';
      case 'png':
        return 'image/png';
      case 'pdf':
        return 'application/pdf';
      // Add more cases for other file types as needed
      default:
        return 'application/octet-stream'; // Default MIME type
    }
  }


// Modify the uploadimageuploadaimage function
  Future<void> uploadimageuploada(String ref, String refTableNmae,
      String selectedFilePath, Uint8List image_timageBytes) async {
    try {

      final Uint8List fileBytes = image_timageBytes!;
      final mimeType = imageuploadalookupMimeType(selectedFilePath);

      FormData formData = FormData.fromMap({
        'file': MultipartFile.fromBytes(
          fileBytes,
          filename: selectedFilePath
              .split('/')
              .last, // Get the file name from the path
          contentType: MediaType.parse(mimeType!),
        ),
      });
await repo.imageuploadaUpload(ref, refTableNmae, formData).then((value) {
        ToastMessageUtil.showToast(
            message: "File uploaded successfully",
            toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Failed to upload file", toastType: ToastType.error);
        },
      );
    } catch (error) {
      print('Error occurred during form submission: $error');
    }
  }

// Modify the lookupMimeType function if needed
  String imageuploadalookupMimeType(String filePath) {
    final ext = filePath.split('.').last;
    switch (ext) {
      case 'jpg':
      case 'jpeg':
        return 'image/jpeg';
      case 'png':
        return 'image/png';
      case 'pdf':
        return 'application/pdf';
      // Add more cases for other file types as needed
      default:
        return 'application/octet-stream'; // Default MIME type
    }
  }


// Modify the uploadaudiosimage function
  Future<void> uploadaudios(String ref, String refTableNmae,
      String selectedFilePath, Uint8List image_timageBytes) async {
    try {

      final Uint8List fileBytes = image_timageBytes!;
      final mimeType = audioslookupMimeType(selectedFilePath);

      FormData formData = FormData.fromMap({
        'file': MultipartFile.fromBytes(
          fileBytes,
          filename: selectedFilePath
              .split('/')
              .last, // Get the file name from the path
          contentType: MediaType.parse(mimeType!),
        ),
      });


     await repo.audiosUpload(ref, refTableNmae, formData).then((value) {
        ToastMessageUtil.showToast(
            message: "File uploaded successfully",
            toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Failed to upload file", toastType: ToastType.error);
        },
      );
    } catch (error) {
      print('Error occurred during form submission: $error');
    }
  }

// Modify the lookupMimeType function if needed
  String audioslookupMimeType(String filePath) {
  final ext = filePath.split('.').last.toLowerCase();
  switch (ext) {
    case 'mp3':
      return 'audio/mpeg';
    case 'wav':
      return 'audio/wav';
    case 'm4a':
      return 'audio/mp4';
    case 'flac':
      return 'audio/flac';
    // Add more cases for other audio formats as needed
    default:
      return 'application/octet-stream'; // Default MIME type
  }
}


// Modify the uploadvideoxximage function
  Future<void> uploadvideoxx(String ref, String refTableNmae,
      String selectedFilePath, Uint8List image_timageBytes) async {
    try {

      final Uint8List fileBytes = image_timageBytes!;
      final mimeType = videoxxlookupMimeType(selectedFilePath);

      FormData formData = FormData.fromMap({
        'file': MultipartFile.fromBytes(
          fileBytes,
          filename: selectedFilePath
              .split('/')
              .last, // Get the file name from the path
          contentType: MediaType.parse(mimeType!),
        ),
      });


  
     await repo.videoxxUpload(ref, refTableNmae, formData).then((value) {
        ToastMessageUtil.showToast(
            message: "File uploaded successfully",
            toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Failed to upload file", toastType: ToastType.error);
        },
      );
    } catch (error) {
      print('Error occurred during form submission: $error');
    }
  }

// Modify the lookupMimeType function if needed
  String videoxxlookupMimeType(String filePath) {
    final ext = filePath.split('.').last.toLowerCase();
    switch (ext) {
      case 'mp4':
        return 'video/mp4';
      case 'mov':
        return 'video/quicktime';
      case 'avi':
        return 'video/x-msvideo';
      case 'wmv':
        return 'video/x-ms-wmv';
      case 'flv':
        return 'video/x-flv';
      case 'mkv':
        return 'video/x-matroska';
      // Add more cases for other file types as needed
      default:
        return 'application/octet-stream'; // Default MIME type
    }
  }







}