import 'dart:convert';

import 'package:guru_app/guru_app.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import 'in_app_receipt_ios.dart';

import 'package:http/http.dart' as http;

import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';

/// Created by Haoyi on 3/5/21
///

class IosReceiptValidator {
  final AppStorePurchaseDetails purchasedDetails;

  ReceiptData? _receiptData;

  IosReceiptValidator(this.purchasedDetails);

  Future<ReceiptData?> _validateReceipt(bool isSandbox) async {
    Log.d("[validate] isSandbox:$isSandbox");

    final iosValidateReceiptPassword =
        GuruApp.instance.appSpec.deployment.iosValidateReceiptPassword;
    if (iosValidateReceiptPassword == null) {
      return null;
    }

    final Map<String, String> headers = <String, String>{
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    };
    final Map<String, String> receiptBody = <String, String>{
      "receipt-data": purchasedDetails.verificationData.serverVerificationData,
      "password": iosValidateReceiptPassword
    };

    final String url = isSandbox
        ? 'https://sandbox.itunes.apple.com/verifyReceipt'
        : 'https://buy.itunes.apple.com/verifyReceipt';

    final body = jsonEncode(receiptBody);

    try {
      final response = await http.post(Uri.parse(url), headers: headers, body: body);
      final json = jsonDecode(response.body);
      return ReceiptData.fromJson(json);
    } catch (error, stacktrace) {
      return null;
    }
  }

  Future<ReceiptData?> validate() async {
    final receiptData = await _validateReceipt(false);
    if (receiptData?.environment == "Sandbox" || receiptData?.status == 21007) {
      return _validateReceipt(true);
    }
    return receiptData;
  }

  Duration? _getReceiptDuration(SubscriptionType type,
      {Duration duration = const Duration(seconds: 0)}) {
    switch (type) {
      case SubscriptionType.nonRenewing:
        return duration;
      default:
        return null;
    }
  }

// List<ReceiptItem> _sortedReceipts(List<ReceiptItem> items, {Duration? duration}) {
//   final result = List.of(items);
//   if (duration == null) {
//     result.sort((a, b) => b.expiresDateInMillis.compareTo(a.expiresDateInMillis));
//     return result;
//   }
//   return result;
// }

//   Future<ReceiptResult> verifySubscriptions(SubscriptionType type) async {
//     final receiptData = await validate();
//     final duration = _getReceiptDuration(type);
//     final checkReceipts =
//         receiptData.getCheckReceipts(type: type, checkIds: ProductIds.iapPremiumIds);
//     final nonCancelledReceipts = checkReceipts.where((receipt) => receipt.cancellationDate == null);
//     if (nonCancelledReceipts.length > checkReceipts.length) {
//       print(
//           "[validate]==>  receipt has ${nonCancelledReceipts.length} items, but only ${checkReceipts.length} were parsed");
//     }
//     final sortedReceipts = _sortedReceipts(checkReceipts, duration: duration);
//
//     if (sortedReceipts.isEmpty) {
//       print("[validate]==> sortedReceipts is Empty");
//       return ReceiptResult(PurchaseStatus.notPurchased);
//     }
//
//     final firstReceiptItem = sortedReceipts[0];
//     print(
//         "[validate]==> firstReceiptItem:${firstReceiptItem.expiresDateInMillis} request:${receiptData.requestDateInMillis}");
//     if (firstReceiptItem.expiresDateInMillis > receiptData.requestDateInMillis) {
//       return ReceiptResult(PurchaseStatus.purchased, items: sortedReceipts);
//     } else {
//       return ReceiptResult(PurchaseStatus.expired,
//           expiredDateInMillis: firstReceiptItem.expiresDateInMillis, items: sortedReceipts);
//     }
//   }
// }
}