import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/data/services/services.dart';
import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/discount.dart';
import 'package:fcs/helpers/paginator.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:logging/logging.dart';

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

  StreamSubscription<QuerySnapshot> listener;

  List<Discount> _discounts = [];
  List<Discount> get discounts =>
      _selectedIndex == 1 ? _discounts : List<Discount>.from(_used.values);

  Paginator _used;
  bool isLoading = false;
  int _selectedIndex = 1;
  set selectedIndex(int index) {
    _selectedIndex = index;
    notifyListeners();
  }

  get selectedIndex => _selectedIndex;

  initData() {
    _selectedIndex = 1;
    _load();

    if (_used != null) _used.close();
    _used = _getUsed();
    _used.load();
  }

  void initUser(user) {
    super.initUser(user);
    _load();
  }

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

  Paginator _getUsed() {
    if (user == null || !user.hasFcsShipments()) return null;

    var pageQuery = Firestore.instance
        .collection("/$discounts_collection")
        .where("status", isEqualTo: fcs_shipment_shipped_status)
        .orderBy("code", descending: false);
    var paginator = new Paginator(pageQuery, rowPerLoad: 20, toObj: (data, id) {
      return Discount.fromMap(data, id);
    });
    return paginator;
  }

  Future<List<Discount>> getDiscount(String userID) async {
    String path = "/$discounts_collection";
    try {
      var q = Firestore.instance
          .collection("$path")
          .where("customer_id", isEqualTo: userID)
          .where("status", isEqualTo: "available");
      var snaps = await q.getDocuments(source: Source.server);
      List<Discount> discounts = snaps.documents.map((snap) {
        if (snap.exists) {
          var s = Discount.fromMap(snap.data, snap.documentID);
          return s;
        }
      }).toList();
      return discounts;
    } catch (e) {
      log.warning("Error!! $e");
    }
    return null;
  }

  Future<void> loadMore() async {
    if (_used.ended || _selectedIndex == 1) return;
    isLoading = true;
    notifyListeners();
    await _used.load(onFinished: () {
      isLoading = false;
      notifyListeners();
    });
  }

  Future<void> refresh() async {
    if (_selectedIndex == 1) return;
    await _used.refresh(onFinished: () {
      notifyListeners();
    });
  }

  @override
  logout() async {
    if (listener != null) await listener.cancel();
    if (_used != null) _used.close();

    _discounts = [];
  }

  Future<void> addDiscount(Discount discount) async {
    return Services.instance.commonService.createDiscount(discount);
  }

  Future<void> updateDiscount(Discount discount) async {
    return Services.instance.commonService.updateDiscount(discount);
  }

  Future<void> deleteDiscount(Discount discount) async {
    return Services.instance.commonService.deleteDiscount(discount.id);
  }
}
