import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/data/services/services.dart';
import 'package:fcs/domain/entities/payment_method.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:logging/logging.dart';

class PaymentMethodModel extends BaseModel {
  final log = Logger('PaymentMethodModel');

  List<PaymentMethod> paymentMethods = [];

  PaymentMethod getPaymentMethod(String id) {
    return paymentMethods.firstWhere((e) => e.id == id, orElse: () => null);
  }

  StreamSubscription<QuerySnapshot> listener;

  PaymentMethodModel() {
    if (listener != null) listener.cancel();
    try {
      listener = Firestore.instance
          .collection("/payment_methods")
          .snapshots()
          .listen((snaps) {
        paymentMethods.clear();
        snaps.documents.forEach((d) {
          paymentMethods.add(PaymentMethod.fromMap(d.data, d.documentID));
        });
        notifyListeners();
      });
    } catch (e) {
      log.warning("error:$e");
    }
  }

  Future<void> addPaymentMethod(PaymentMethod paymentMethod) async {
    Services.instance.commonService.createPaymentMethod(paymentMethod);
  }

  Future<void> updatePaymentMethod(PaymentMethod paymentMethod) async {
    Services.instance.commonService.updatePaymentMethod(paymentMethod);
  }

  Future<void> deletePaymentMethod(String id) async {
    Services.instance.commonService.deletePayment(id);
  }
}
