// ignore_for_file: curly_braces_in_flow_control_structures, prefer_is_empty import 'dart:developer'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/pages/about_property_page/about_property_model.dart'; import 'package:hub/pages/about_property_page/about_property_screen.dart'; import 'package:hub/shared/helpers/database/database_helper.dart'; import 'package:hub/shared/helpers/license/license_helper.dart'; import 'package:rxdart/rxdart.dart'; import 'package:sqflite/sqflite.dart'; class LicenseService { static final LicenseService _instance = LicenseService._internal(); factory LicenseService() => _instance; LicenseService._internal(); final _licenseSubject = BehaviorSubject>(); Stream> get licenseStream => _licenseSubject.stream; Future cleanLicense() async { _licenseSubject.add([]); } Future setupLicense(Database database) async { final List inactiveModuleKey = InactiveModuleKey.values.map((e) => e.value).toList(); final List activeModuleKey = ActiveModuleKey.values.map((e) => e.value).toList(); await LicenseHelper().setByKey(inactiveModuleKey, 'INVISIVEL'); await LicenseHelper().setByKey(activeModuleKey, 'VISIVEL'); _licenseSubject.add([...activeModuleKey]); } Future fetchLicenses() async { try { log('Obtendo licenças...'); final response = await PhpGroup.getLicense(); final dynamic responseBody = response.jsonBody; log('Licenças obtidas: $responseBody'); if (response.jsonBody is! List) { late final String error; if (response.jsonBody is Map) error = response.jsonBody['error_msg']; else error = 'Erro desconhecido'; throw Exception('Erro ao consultar licenças: $error'); } if (responseBody == []) { await setupLicense(DatabaseStorage.database); _licenseSubject.add([]); return false; } for (var element in responseBody) { if (licenseContainsKey(element['key'])) { _saveModule(element); } } _licenseSubject.add(responseBody); return true; } catch (e) { log('Erro ao obter licenças: $e'); await setupLicense(DatabaseStorage.database); return false; } } static bool licenseContainsKey(final String key) { return Module.values.map((e) => e.value).toList().contains(key); } static Future _saveModule(final dynamic body) async { if (body is Map) { log('Salvando módulo: ${body.toString()}'); await LicenseHelper().s(body['key'], body); log('body[key]: ${body['key']}'); if (body['key'] == Module.pets.value) if (body['display'] == 'VISIVEL') { await LicenseHelper().s(Module.petsHistory.value, body); } if (AboutPropertyModules.values.any((e) => e.value == body['key']) && body['display'] == 'VISIVEL') { await LicenseHelper().s(Module.aboutProperty.value, body); } } } }