diff --git a/Frontend/lib/mih_services/mih_currency_exchange_rate_services.dart b/Frontend/lib/mih_services/mih_currency_exchange_rate_services.dart new file mode 100644 index 00000000..091a2554 --- /dev/null +++ b/Frontend/lib/mih_services/mih_currency_exchange_rate_services.dart @@ -0,0 +1,73 @@ +import 'dart:convert'; + +import 'package:mzansi_innovation_hub/mih_components/mih_objects/currency.dart'; +import 'package:supertokens_flutter/http.dart' as http; + +class MihCurrencyExchangeRateServices { + static Future> getCurrencyObjectList() async { + final response = await http.get(Uri.parse( + "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.min.json")); + if (response.statusCode == 200) { + final Map jsonMap = json.decode(response.body); + List currencies = []; + jsonMap.forEach((code, dynamic nameValue) { + final String name = nameValue is String ? nameValue : 'Unknown Name'; + currencies.add(Currency(code: code, name: name)); + }); + currencies.sort((a, b) => a.name.compareTo(b.name)); + return currencies; + } else { + throw Exception('failed to fatch currencies'); + } + } + + static Future> getCurrencyCodeList() async { + final response = await http.get(Uri.parse( + "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.min.json")); + if (response.statusCode == 200) { + final Map jsonMap = json.decode(response.body); + List currencies = []; + jsonMap.forEach((code, dynamic nameValue) { + final String name = nameValue is String ? nameValue : 'Unknown Name'; + currencies.add("$code - $name"); + }); + currencies.sort(); + return currencies; + } else { + throw Exception('failed to fatch currencies'); + } + } + + static Future getCurrencyExchangeValue( + String fromCurrencyCode, + String toCurrencyCode, + ) async { + final response = await http.get(Uri.parse( + "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/$fromCurrencyCode.min.json")); + if (response.statusCode == 200) { + final Map jsonResponse = json.decode(response.body); + final Map? baseCurrencyData = + jsonResponse[fromCurrencyCode]; + + if (baseCurrencyData != null) { + // Access the value for the target currency (e.g., "usd") + final dynamic rateValue = baseCurrencyData[toCurrencyCode]; + + if (rateValue is num) { + // Check if it's a number (int or double) + return rateValue.toDouble(); + } else { + // Handle cases where the rate might not be a number or is missing + print( + 'Warning: Rate for $toCurrencyCode in $fromCurrencyCode is not a number or missing.'); + return 0; + } + } else { + throw Exception( + 'Base currency "$fromCurrencyCode" data not found in response.'); + } + } else { + throw Exception('failed to fatch currencies'); + } + } +}