import 'dart:ui';

import 'package:firka/core/settings.dart';
import 'package:firka/app/app_state.dart';

import 'package:firka/ui/theme/style.dart';
import 'package:kreta_api/kreta_api.dart';

int roundGrade(double grade) {
  final rounding = initData.settings
      .group("settings")
      .subGroup("application")
      .subGroup("rounding");
  if (grade < 1 + rounding.dbl("1")) {
    return 1;
  }
  if (grade < 2 + rounding.dbl("2")) {
    return 2;
  }
  if (grade < 3 + rounding.dbl("3")) {
    return 3;
  }
  if (grade < 4 + rounding.dbl("4")) {
    return 4;
  }

  return 5;
}

int percentageToGrade(int grade) {
  if (grade < 50) {
    return 1;
  }
  if (grade < 60) {
    return 2;
  }
  if (grade < 70) {
    return 3;
  }
  if (grade < 80) {
    return 4;
  }

  return 5;
}

Color getGradeColor(double grade) {
  switch (roundGrade(grade)) {
    case 2:
      return appStyle.colors.grade2;
    case 3:
      return appStyle.colors.grade3;
    case 4:
      return appStyle.colors.grade4;
    case 5:
      return appStyle.colors.grade5;
    default:
      return appStyle.colors.grade1;
  }
}

(int total, List<int> countsByGrade) getGradeDistribution(List<Grade> grades) {
  final filtered = grades
      .where((g) => g.type.name != "felevi_jegy_ertekeles")
      .toList();
  final counts = [0, 0, 0, 0, 0];
  for (final g in filtered) {
    if (g.numericValue == null) continue;
    final value = g.valueType.name == "Szazalekos"
        ? percentageToGrade(g.numericValue!.round())
        : g.numericValue!.round().clamp(1, 5);
    counts[value - 1]++;
  }
  return (filtered.length, counts);
}

extension GradeListExtension on List<Grade> {
  double getAverageBySubject(Subject subject) {
    var weightTotal = 0.00;
    var sum = 0.00;

    for (var grade in this) {
      if (grade.subject.uid == subject.uid) {
        if (grade.numericValue != null) {
          var weight = (grade.weightPercentage ?? 100) / 100.0;
          weightTotal += weight;

          sum += grade.numericValue! * weight;
        }
      }
    }

    return sum / weightTotal;
  }
}
