import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/domain/entities/faq.dart';
import 'package:fcs/helpers/firebase_helper.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:logging/logging.dart';

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

  List<FAQ> faqs = [];

  FAQ getFAQ(String id) {
    return faqs.firstWhere((e) => e.id == id, orElse: () => null);
  }

  StreamSubscription<QuerySnapshot> listener;

  FAQModel() {
    if (listener != null) listener.cancel();
    try {
      listener = Firestore.instance
          .collection("/faqs")
          .orderBy("sn", descending: false)
          .snapshots()
          .listen((snaps) {
        faqs.clear();
        snaps.documents.forEach((d) {
          faqs.add(FAQ.fromMap(d.data, d.documentID));
        });
        notifyListeners();
      });
    } catch (e) {
      log.warning("error:$e");
    }
  }

  Future<void> addFAQ(FAQ faq) async {
    await request("/faqs", "POST",
        payload: faq.toMap(), token: await getToken());
  }

  Future<void> updateFAQ(FAQ faq) async {
    await request("/faqs", "PUT",
        payload: faq.toMap(), token: await getToken());
  }

  Future<void> deleteFAQ(FAQ faq) async {
    await request("/faqs", "DELETE",
        payload: faq.toMap(), token: await getToken());
  }
}
