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/carton.dart';
import 'package:fcs/domain/vo/message.dart';
import 'package:fcs/helpers/paginator.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:logging/logging.dart';

class DeliveryModel extends BaseModel {
  final log = Logger('DeliveryModel');
  List<Carton> get cartons =>
      _selectedIndex == 1 ? _cartons : List<Carton>.from(_delivered.values);

  Paginator _delivered;
  int _selectedIndex = 1;
  bool isLoading = false;
  List<Carton> _cartons = [];
  StreamSubscription<QuerySnapshot> listener;

  set selectedIndex(int index) {
    _selectedIndex = index;
    notifyListeners();
  }

  get selectedIndex => _selectedIndex;

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

    if (_delivered != null) _delivered.close();
    _delivered = _getDelivered();
    _delivered.load();
  }

  Future<void> _loadCartons() async {
    if (user == null || !user.hasDeliveries()) return;
    String path = "/$cartons_collection/";
    if (listener != null) listener.cancel();
    _cartons = [];
    try {
      listener = Firestore.instance
          .collection("$path")
          .where("status", isEqualTo: carton_shipped_status)
          .where("carton_type", whereIn: [
            carton_from_packages,
            carton_from_shipments,
            carton_small_bag
          ])
          .where("is_deleted", isEqualTo: false)
          .orderBy("carton_number", descending: false)
          .snapshots()
          .listen((QuerySnapshot snapshot) {
            _cartons.clear();
            _cartons = snapshot.documents.map((documentSnapshot) {
              var s = Carton.fromMap(
                  documentSnapshot.data, documentSnapshot.documentID);
              return s;
            }).toList();
            notifyListeners();
          });
    } catch (e) {
      log.warning("Error!! $e");
    }
  }

  Paginator _getDelivered() {
    if (user == null || !user.hasDeliveries()) return null;

    var pageQuery = Firestore.instance
        .collection("/$cartons_collection")
        .where("is_delivered", isEqualTo: true)
        .where("status", whereIn: [carton_delivered_status]).where("is_deleted",
            isEqualTo: false);
    var paginator = new Paginator(pageQuery, rowPerLoad: 20, toObj: (data, id) {
      return Carton.fromMap(data, id);
    });
    return paginator;
  }

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

  Future<void> refresh() async {
    if (_selectedIndex == 1) return;

    await _delivered.refresh(onFinished: () {
      notifyListeners();
    });
  }

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

  @override
  logout() async {
    if (listener != null) await listener.cancel();
    if (_delivered != null) _delivered.close();
    _cartons = [];
  }

  Future<void> deliver(Carton carton) {
    return Services.instance.cartonService.deliver(carton);
  }
}
