import 'dart:async';

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

class MarketModel extends BaseModel {
  final log = Logger('MarketModel');
  StreamSubscription<QuerySnapshot> listener;
  List<Market> markets = [];

  MarketModel() {
    _loadMarkets();
  }

  Future<void> _loadMarkets() async {
    try {
      if (listener != null) listener.cancel();

      listener = Firestore.instance
          .collection("/$config_collection/$setting_doc_id/$markets_collection")
          .snapshots()
          .listen((QuerySnapshot snapshot) {
        markets.clear();
        markets = snapshot.documents.map((documentSnapshot) {
          var user = Market.fromMap(
              documentSnapshot.data, documentSnapshot.documentID);
          return user;
        }).toList();
        notifyListeners();
      });
    } catch (e) {
      log.warning("Error!! $e");
    }
  }

  Future<void> addMarket(String marketName) async {
    await request("/markets", "POST",
        payload: {"name": marketName}, token: await getToken());
  }

  Future<void> deleteMarket(String id) async {
    await request("/markets", "DELETE",
        payload: {"id": id}, token: await getToken());
  }
}
