import 'package:get/get.dart';
import '../models/tank_model.dart';

class GraphController extends GetxController {
  final listTankModel = <TankModel>[].obs;
  final sumYearKm = 0.0.obs;
  final sumYearLiters = 0.0.obs;
  final sumYearPrice = 0.0.obs;
  final averagePricePerLiter = 0.0.obs;

  @override
  void onInit() {
    if (Get.arguments != null) {
      var args = Get.arguments as List<TankModel>;
      listTankModel.addAll(args);
      _calcSumms();
    }
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  // Calculate yearly summaries
  void _calcSumms() {
    if (listTankModel.length < 2) {
      sumYearKm.value = 0.0;
      sumYearLiters.value = 0.0;
      sumYearPrice.value = 0.0;
      return;
    }

    // Sort by date to calculate km correctly
    listTankModel.sort((a, b) {
      var dateA = DateTime.tryParse(a.szDate)!;
      var dateB = DateTime.tryParse(b.szDate)!;
      return dateA.compareTo(dateB);
    });

    var firstOdometer = double.tryParse(listTankModel.first.szOdometer) ?? 0.0;
    var lastOdometer = double.tryParse(listTankModel.last.szOdometer) ?? 0.0;

    sumYearKm.value = lastOdometer - firstOdometer;

    double totalLiters = 0.0;
    double totalPrice = 0.0;

    for (var tank in listTankModel) {
      totalLiters += double.tryParse(tank.szLiters) ?? 0.0;
      totalPrice += double.tryParse(tank.szPriceTotal) ?? 0.0;
    }

    sumYearLiters.value = totalLiters;
    sumYearPrice.value = totalPrice;
    averagePricePerLiter.value = totalPrice / totalLiters;
  }
}
