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 {
  var historyPoint = Rxn<ListHistoryResponseModel>();
  var transactionSummary = Rxn<TransactionSummaryByDateModel>();
  final RxInt selectedTabIndex = 0.obs;
  DateTime selectedDate = DateTime.now();

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

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

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

  Future<void> _getTransactionGetSummaryByDate() async {
    final body = {
      'month': selectedDate.month,
      'year': selectedDate.year,
      'lang': 'vi',
    };
    final res = await client.transactionGetSummaryByDate(body);
    transactionSummary.value = res.data;
  }

  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',
    };
    final res = await client.transactionHistoryGetList(body);
    historyPoint.value = res.data;
  }
}