import 'package:flutter/material.dart'; import 'package:sqflite/sqflite.dart'; import '../services/services.dart'; import '../models/models.dart'; class VariableViewModel extends ChangeNotifier { String _busqueda = ""; String get busqueda => _busqueda; List _variables = []; bool _isLoading = false; Variable? _selectedVariable; List get variables => _variables; Variable? get selectedVariable => _selectedVariable; bool get isLoading => _isLoading; int _currentPage = 1; int _totalVariables = 0; int _limit = 10; int get currentPage => _currentPage; int get totalVariables => _totalVariables; int get totalPages => (_totalVariables / _limit).ceil(); setBusqueda(String value) { _busqueda = value; notifyListeners(); } void selectVariable(Variable variable) { _selectedVariable = variable; notifyListeners(); } Future fetchLocalAll({int page = 1}) async { _currentPage = page; var db = await RepoService().db; int? count = Sqflite.firstIntValue( await db!.rawQuery('SELECT COUNT(*) FROM Variable')); _totalVariables = count ?? 0; int offset = (_limit * (page - 1)); var query = await db.query('Variable', orderBy: 'id asc', limit: _limit, offset: offset); _variables = query.map((element) => Variable.fromJson(element)).toList(); notifyListeners(); } Future fetchLocalByName({required String nombre}) async { var db = await RepoService().db; var query = await db!.query( 'Variable', where: 'nombre LIKE "%$nombre%"', orderBy: 'id asc', ); List aux = []; for (var element in query) { Variable variable = Variable.fromJson(element); aux.add(variable); } _variables = aux; notifyListeners(); } Future addVariable(Variable variable) async { await RepoService().guardar(variable); fetchLocalAll(); } Future updateVariable(Variable variable) async { setIsLoading(true); try { await RepoService().guardar(variable); fetchLocalAll(); } catch (e) { print('Error updating variable: $e'); } setIsLoading(false); } Future deleteVariable(int id) async { await RepoService().eliminar(id); fetchLocalAll(); } void setIsLoading(bool loading) { _isLoading = loading; notifyListeners(); } void nextPage() { if (_currentPage < totalPages) { fetchLocalAll(page: _currentPage + 1); } } void previousPage() { if (_currentPage > 1) { fetchLocalAll(page: _currentPage - 1); } } Future isVariableActive(String clave) async { var db = await RepoService().db; var result = await db!.query( 'Variable', where: 'clave = ?', whereArgs: [clave], ); if (result.isNotEmpty) { var variable = Variable.fromJson(result.first); return variable.activo == true; } return false; } Future getVariableByClave(String nombre) async { var db = await RepoService().db; var result = await db!.query( 'Variable', where: 'nombre = ?', whereArgs: [nombre], ); if (result.isNotEmpty) { return Variable.fromJson(result.first); } return null; } }