import 'package:daily_challenge/daily_challenge_package.dart';
import 'package:daily_challenge/data/db/entities/entities.dart';
import 'package:example/route/router.dart';
import 'package:guru_utils/datetime/datetime_utils.dart';
import 'package:guru_utils/log/log.dart';
import 'package:guru_utils/number/number_utils.dart';
import 'package:guru_utils/router/router.dart';

/// Created by Haoyi on 2023/10/9

class DailyChallengeDelegateImpl extends DailyChallengeDelegate {
  @override
  DailyChallengeAccessMode getAccessMode(
      DateTime dateTime, List<DailyChallengeEntity>? entities) {
    return dateTime.month % 2 == 0 && dateTime.day % 5 == 0
        ? DailyChallengeAccessMode.reward
        : DailyChallengeAccessMode.free;
  }

  @override
  void playOrReplay(DailyChallengeRequest request) async {
    // if (request.focusDate.day == 11) {
    //   request.update(DailyChallengeState(
    //       DateTimeUtils.yyyyMMddBuild(request.focusDate),
    //       DateTimeUtils.currentTimeInMillis(),
    //       0));
    //   return;
    // }
    // int progress = getDailyProgress(request.focusDate, request.entities);
    // if (progress >= 100) {
    //   progress = 0;
    // }
    // int intProgress = (progress + 10).clamp(0, 100).toInt();
    // request.update(DailyChallengeState(
    //     DateTimeUtils.yyyyMMddBuild(request.focusDate),
    //     DateTimeUtils.currentTimeInMillis(),
    //     intProgress));
    // Log.d("playOrReplay ${request.focusDate} $progress $intProgress");
      request.update(DailyChallengeState(
          DateTimeUtils.yyyyMMddBuild(request.focusDate),
          DateTimeUtils.currentTimeInMillis(),
          100));
  }

  @override
  Future<DailyChallengeConfig> loadConfig() async {
    return DailyChallengeConfig(DateTime(2022, 1, 23), Routes.awards, [
      for (int i = 0; i < 12; ++i)
        TrophyAsset(
            initial:
                "assets/images/daily_challenge/trophies/grey${NumberUtils.twoDigits(i + 1)}.png",
            achieved: [
              "assets/images/daily_challenge/trophies/gold${NumberUtils.twoDigits(i + 1)}.png"
            ])
    ]);
  }

  @override
  int getDailyProgress(DateTime dateTime, List<DailyChallengeEntity> entities) {
    if (entities.isNotEmpty) {
      final progress = (entities
          .map((e) => (e.status == DailyChallengeStatus.completed)
          ? 100
          : e.progress)
          .reduce((value, element) => value + element) ~/
          entities.length);
      Log.d("getDailyProgress $dateTime $progress");
      return progress.clamp(0, 100);
    }
    return 0;
  }
}
