import 'dart:async';

import 'package:guru_app/financial/asset/assets_model.dart';
import 'package:guru_app/financial/data/db/order_database.dart';
import 'package:guru_app/financial/manifest/manifest.dart';
import 'package:guru_app/financial/product/product_model.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:guru_utils/id/id_utils.dart';
import 'package:guru_utils/datetime/datetime_utils.dart';

/// Created by Haoyi on 6/2/21

class IapRequest {
  final IapProduct product;
  final OrderEntity order;
  final Completer<bool> completer;

  ProductId get productId => product.productId;

  IapRequest(this.product, this.order, this.completer);

  void response(bool result) {
    if (!completer.isCompleted) {
      completer.complete(result);
    }
  }
}

class PurchaseError implements Exception {
  final String msg;

  PurchaseError(this.msg);
}

class IapProduct implements Product {
  @override
  final ProductId productId;

  final ProductDetails details;

  final ProductDetails? offerDetails;

  @override
  final Manifest manifest;

  String get sku => productId.sku;

  IapProduct(this.productId, this.details, this.manifest, {this.offerDetails});

  bool isConsumable() {
    return productId.isConsumable;
  }

  @override
  String toString() {
    return 'IapProduct{productId: $productId}';
  }

  @override
  OrderEntity createOrder() {
    return OrderEntity(
        orderId: IdUtils.uuidV4(),
        sku: productId.sku,
        state: TransactionState.pending,
        attr: productId.attr,
        method: TransactionMethod.iap.index,
        currency: details.currencyCode ?? "USD",
        cost: details.rawPrice,
        category: manifest.category,
        timestamp: DateTimeUtils.currentTimeInMillis(),
        manifest: manifest);
  }

// @override
// TransactionEntity buildTransaction({String? tid}) {
//   return TransactionEntity(
//       tid: tid,
//       sku: productId.sku,
//       state: TransactionStates.pending,
//       attr: productId.attr,
//       method: TransactionMethods.iap,
//       currency: details.currencySymbol,
//       cost: details.rawPrice,
//       timestamp: DateTimeUtils.currentTimeInMillis(),
//       manifest: manifest);
// }
}

class IapAsset extends Asset {
  final PurchaseDetails details;

  IapAsset(ProductId productId, OrderEntity entity, this.details) : super(productId, entity);

  IapAsset copyWith({OrderEntity? order, PurchaseDetails? details}) {
    return IapAsset(productId, order ?? this.order, details ?? this.details);
  }

  @override
  String toString() {
    return 'IapPurchased{productId: $productId, item: $details}';
  }

// @override
// Manifest? get manifest => ;
}
