import 'dart:convert'; // Para convertir datos a JSON import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:primer_practica/src/http_api/category_service.dart'; import 'package:primer_practica/src/models/categoryModel.dart'; class CategoryController { final Connectivity _connectivity = Connectivity(); // Método para obtener las categorías Future> getCategories() async { Map mapResp = { 'ok': false, 'message': 'No hay categorias', 'data': null }; ConnectivityResult connectivityResult = (await _connectivity.checkConnectivity()); if (connectivityResult != ConnectivityResult.none) { if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) { CategoryService categoryApi = CategoryService(); Map respGet = await categoryApi.getCategories(); if (respGet['statusCode'] == 200) { try { var decodeResp = json.decode(respGet['body']); List listCategories = CategoryModel.fromJsonArray(decodeResp['data']); mapResp['ok'] = true; mapResp['message'] = "${listCategories.length} categorías encontradas"; mapResp['data'] = listCategories; } catch (e) { mapResp['message'] = "Error en decodificación: $e"; } } else { mapResp['message'] = "${respGet['body']}"; } } } return mapResp; } // Método para agregar una categoría Future> addCategory(CategoryModel category) async { Map mapResp = { 'ok': false, 'message': 'No se pudo agregar la categoría' }; ConnectivityResult connectivityResult = (await _connectivity.checkConnectivity()); if (connectivityResult != ConnectivityResult.none) { if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) { CategoryService categoryApi = CategoryService(); Map respPost = await categoryApi.postCategory(category); if (respPost['statusCode'] == 201) { mapResp['ok'] = true; mapResp['message'] = 'Categoría agregada exitosamente'; } else { mapResp['message'] = "${respPost['body']}"; } } } return mapResp; } }