import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import 'models/history_point_models.dart';
import 'models/transaction_summary_by_date_model.dart';

class HistoryPointViewModel extends RestfulApiViewModel {
  final Rxn<ListHistoryResponseModel> historyPoint = Rxn<ListHistoryResponseModel>();
  final Rxn<TransactionSummaryByDateModel> transactionSummary = Rxn<TransactionSummaryByDateModel>();
  final RxInt selectedTabIndex = 0.obs;
  DateTime selectedDate = DateTime.now();

  @override
  void onInit() {
    super.onInit();
    freshData();
  }

  void changeDate(bool prevMonth) {
    selectedDate = DateTime(selectedDate.year, selectedDate.month + (prevMonth ? -1 : 1), 1);
    freshData();
  }

  Future<void> freshData() async {
    await Future.wait<void>([
      _getTransactionGetSummaryByDate(),
      _getTransactionSummaryByDateModel(),
    ], eagerError: false);
  }

  Future<void> _getTransactionGetSummaryByDate() async {
    final body = {
      'month': selectedDate.month,
      'year': selectedDate.year,
      'lang': 'vi',
    };
    
    await callApi<TransactionSummaryByDateModel>(
      request: () => client.transactionGetSummaryByDate(body),
      onSuccess: (data, _) {
        transactionSummary.value = data;
      },
      onFailure: (msg, _, _) async {
        transactionSummary.value = null;
      },
    );
  }

  Future<void> _getTransactionSummaryByDateModel() async {
    historyPoint.value = null;
    final body = {
      'transaction_happened_in_year': selectedDate.year,
      'transaction_happened_in_month': selectedDate.month,
      'transaction_types': selectedTabIndex.value == 1 ? 'RD,AD': (selectedTabIndex.value == 0 ? 'RW,AD' : ''),
      'limit': 1000,
      'start': 0,
      'lang': 'vi',
    };
    
    await callApi<ListHistoryResponseModel>(
      request: () => client.transactionHistoryGetList(body),
      onSuccess: (data, _) {
        historyPoint.value = data;
      },
      onFailure: (msg, _, _) async {
        historyPoint.value = null;
      },
    );
  }
}