import 'dart:io';

import 'package:logging/logging.dart';
import 'package:url_launcher/url_launcher.dart';

import '../persistence/persistence.dart';
import '../remote_config/remote_config.dart';

final Logger _log = Logger('RatingHelper');

class RatingHelper {
  static const int _maxShowTimes = 3; //最多弹框次数
  static const int _showTimeHours = 24; // 24小时
  static const String _googlePlayUrl = "https://play.google.com/store/apps/details?id=jigsort.solitaire.jigsaw.match.games";
  static const String _appStoreUrl = "https://apps.apple.com/us/app/jigsort.solitaire.jigsaw.match.games/id6499138123";

  static String get appStoreUrl {
    if (Platform.isAndroid) {
      return _googlePlayUrl;
    }
    if (Platform.isIOS) {
      return _appStoreUrl;
    }
    return _googlePlayUrl;
  }

  static Future<bool> shouldShowRateDialog(int doneLevelCount) async {
    // 1. 是否已经评过分
    double rating = Persistence().rating;
    if (rating > 0) {
      _log.info("shouldShowRateDialog false. already rated, rating: $rating");
      return false;
    }

    // 2. 检查已经弹过几次框
    int rateShowTimes = Persistence().rateShowTimes;
    if (rateShowTimes >= _maxShowTimes) {
      _log.info("shouldShowRateDialog false. rateShowTimes limit");
      return false;
    }
    // ios 只弹框一次
    if (Platform.isIOS && rateShowTimes >= 1) {
      _log.info("shouldShowRateDialog false. iOS rateShowTimes limit");
      return false;
    }

    // 3. 检查上次弹框时间，需要超过24小时才能再次弹框
    DateTime now = DateTime.now();
    DateTime lastRateShowTime = Persistence().rateLastShowTime;
    if (now.difference(lastRateShowTime).inHours < _showTimeHours) {
      _log.info("shouldShowRateDialog false. show time in 24 hours");
      return false;
    }

    //4. 用户完成了n个关卡才弹框
    int rateLevelsCount = RemoteConfig().rateUsLevelCount;
    int completedCount = doneLevelCount;
    if (completedCount < rateLevelsCount) {
      _log.info("shouldShowRateDialog false. must finish at lease $rateLevelsCount works");
      return false;
    }

    _log.info("shouldShowRateDialog true!");
    return true;
  }

  // 用户点了取消按钮未评分
  static onRateCancel() async {
    // 写入弹框次数+1
    Persistence().rateShowTimes++;

    // 写入弹框时间
    Persistence().rateLastShowTime = DateTime.now();
  }

  // 用户选择评分并正常提交
  static onRateSubmmit(double rating) async {
    // 写入弹框次数+1
    Persistence().rateShowTimes++;

    // 写入弹框时间
    Persistence().rateLastShowTime = DateTime.now();

    // 写入评分
    Persistence().rating = rating;

    // 5星评分，跳转到应用商店评价页面
    if (rating >= 5.0 && Platform.isAndroid) {
      _linkLaunch(appStoreUrl);
    }
  }

  // 页面跳转
  static _linkLaunch(String link) async {
    Uri url = Uri.parse(link);
    if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
      throw Exception('Could not launch $url');
    }
  }
}
