import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:marco/model/user_permission.dart'; import 'package:marco/model/employee_info.dart'; import 'package:marco/model/projects_model.dart'; class PermissionService { // Cache to store the fetched user profile data per token static final Map> _userDataCache = {}; // Method to fetch the user profile data (permissions, employee info, and projects) static Future> fetchAllUserData(String token) async { // Check if the data for this token is already cached if (_userDataCache.containsKey(token)) { return _userDataCache[token]!; } try { // Fetch data from the API final response = await http.get( Uri.parse('https://stageapi.marcoaiot.com/api/user/profile'), headers: {'Authorization': 'Bearer $token'}, ); if (response.statusCode == 200) { final data = json.decode(response.body)['data']; // Parse and extract relevant information final permissions = _parsePermissions(data['featurePermissions']); final employeeInfo = _parseEmployeeInfo(data['employeeInfo']); final projectsInfo = _parseProjectsInfo(data['projects']); // Cache the processed data for later use final allUserData = { 'permissions': permissions, 'employeeInfo': employeeInfo, 'projects': projectsInfo, }; _userDataCache[token] = allUserData; return allUserData; } else { final errorData = json.decode(response.body); throw Exception('Failed to load data: ${errorData['message']}'); } } catch (e) { print('Error fetching user data: $e'); throw Exception('Error fetching user data: $e'); } } // Helper method to parse permissions from raw data static List _parsePermissions(List featurePermissions) { return featurePermissions .map((id) => UserPermission.fromJson({'id': id})) .toList(); } // Helper method to parse employee info from raw data static EmployeeInfo _parseEmployeeInfo(Map employeeData) { return EmployeeInfo.fromJson(employeeData); } // Helper method to parse projects from raw data static List _parseProjectsInfo(List projectIds) { return projectIds.map((id) => ProjectInfo.fromJson(id)).toList(); } }