import 'dart:async';
import 'dart:io';

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/package.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/helpers/firebase_helper.dart';
import 'package:fcs/helpers/paginator.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as Path;

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

  StreamSubscription<QuerySnapshot> listener;

  List<Package> get packages => _menuSelectedIndex == 1
      ? _packages
      : List<Package>.from(_delivered.values);

  List<Package> _packages = [];

  Paginator _delivered;
  bool isLoading = false;
  int _menuSelectedIndex = 1;

  set menuSelectedIndex(int index) {
    _menuSelectedIndex = index;
    notifyListeners();
  }

  get menuSelectedIndex => _menuSelectedIndex;

  initData(bool forCustomer) {
    logout();
    _menuSelectedIndex = 1;
    _loadPackages(forCustomer);
    _delivered = _getDelivered(forCustomer);
    _delivered.load();
  }

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

  Future<void> loadMore({bool isCustomer}) async {
    if (_delivered.ended || menuSelectedIndex == 1)
      return; // when delivered menu is not selected return
    isLoading = true;
    notifyListeners();
    await _delivered.load(onFinished: () {
      isLoading = false;
      notifyListeners();
    });
  }

  Future<void> refresh({bool isCustomer}) async {
    if (menuSelectedIndex == 1)
      return; // when delivered menu is not selected return
    await _delivered.refresh(onFinished: () {
      notifyListeners();
    });
  }

  Paginator _getDelivered(bool isCustomer) {
    if (!isCustomer) {
      if (user == null ||
          !((user.hasPackages() ||
              user.hasReceiving() ||
              user.hasProcessing()))) throw "No privilege";
    }
    var pageQuery = Firestore.instance
        .collection("/$packages_collection")
        .where("is_delivered", isEqualTo: true)
        .where("is_deleted", isEqualTo: false);
    if (isCustomer) {
      pageQuery = pageQuery.where("user_id", isEqualTo: user.id);
    }
    pageQuery = pageQuery.orderBy("status_date", descending: true);
    var paginator = new Paginator(pageQuery, rowPerLoad: 20, toObj: (data, id) {
      return Package.fromMap(data, id);
    });
    return paginator;
  }

  Future<void> _loadPackages(bool forCustomer) async {
    if (user == null) return;
    if (!forCustomer &&
        !((user.hasPackages() || user.hasReceiving() || user.hasProcessing())))
      return;
    String path = "/$packages_collection";
    if (listener != null) listener.cancel();
    _packages = [];

    try {
      var q = Firestore.instance
          .collection("$path")
          .where("is_delivered", isEqualTo: false)
          .where("is_deleted", isEqualTo: false);

      if (forCustomer) {
        q = q.where("user_id", isEqualTo: user.id);
      }
      q = q.orderBy("tracking_id", descending: false);
      listener = q.snapshots().listen((QuerySnapshot snapshot) {
        _packages.clear();
        _packages = snapshot.documents.map((documentSnapshot) {
          var package = Package.fromMap(
              documentSnapshot.data, documentSnapshot.documentID);
          return package;
        }).toList();
        notifyListeners();
      });
    } catch (e) {
      log.warning("Error!! $e");
    }
  }

  Future<Package> getPackage(String id) async {
    if (user == null) return null;
    String path = "/$packages_collection";
    try {
      DocumentSnapshot snap =
          await Firestore.instance.collection("$path").document(id).get();
      if (snap.exists) {
        var package = Package.fromMap(snap.data, snap.documentID);
        return package;
      }
    } catch (e) {
      log.warning("Error!! $e");
    }
    return null;
  }

  Future<Package> lookupPackage(String trackingID) async {
    if (user == null) return null;
    String path = "/$packages_collection";

    try {
      var qsnap = await Firestore.instance
          .collection("$path")
          .where("tracking_id", isEqualTo: trackingID)
          .where("has_user_id", isEqualTo: false)
          .where("is_deleted", isEqualTo: false)
          .getDocuments(source: Source.server);
      if (qsnap.documents.length > 0) {
        var snap = qsnap.documents[0];
        if (snap.exists) {
          var package = Package.fromMap(snap.data, snap.documentID);
          return package;
        }
      }

      qsnap = await Firestore.instance
          .collection("$path")
          .where("tracking_id", isEqualTo: trackingID)
          .where("user_id", isEqualTo: user.id)
          .where("is_deleted", isEqualTo: false)
          .getDocuments(source: Source.server);
      if (qsnap.documents.length > 0) {
        var snap = qsnap.documents[0];
        if (snap.exists) {
          var package = Package.fromMap(snap.data, snap.documentID);
          return package;
        }
      }
    } catch (e) {
      log.warning("Error!! $e");
    }
    return null;
  }

  Future<List<Package>> getPackages(String userID, List<String> status) async {
    List<Package> packages = [];
    try {
      var snaps = await Firestore.instance
          .collection("/$packages_collection")
          .where("status", whereIn: status)
          .where("user_id", isEqualTo: userID)
          .where("is_deleted", isEqualTo: false)
          .getDocuments(source: Source.server);
      packages = snaps.documents.map((documentSnapshot) {
        var p =
            Package.fromMap(documentSnapshot.data, documentSnapshot.documentID);
        return p;
      }).toList();
    } catch (e) {
      log.warning("Error!! $e");
    }
    return packages;
  }

  Future<List<User>> searchUser(String term) {
    return Services.instance.userService.searchUser(term);
  }

  Future<List<Package>> searchPackage(String term) {
    return Services.instance.packageService.searchPackage(term);
  }

  Future<void> createPackages(User user, List<Package> packages) {
    return Services.instance.packageService
        .createPackages(packages, user.fcsID);
  }

  Future<void> createReceiving(
      User user, Package package, List<File> files) async {
    if (user != null) {
      package.fcsID = user.fcsID;
    }
    if (files != null) {
      if (files.length > 5) throw Exception("Exceed number of file upload");
      package.photoUrls = package.photoUrls == null ? [] : package.photoUrls;
      for (File f in files) {
        String path = Path.join(pkg_files_path);
        String url = await uploadStorage(path, f);
        package.photoUrls.add(url);
      }
    }
    return Services.instance.packageService.createReceiving(package);
  }

  Future<void> updateReceiving(User user, Package package, List<File> files,
      List<String> deletedUrls) async {
    if (user != null) {
      package.fcsID = user.fcsID;
    }
    if (deletedUrls != null) {
      for (String url in deletedUrls) {
        package.photoUrls.remove(url);
      }
      await deleteStorageFromUrls(deletedUrls);
    }

    if (files != null) {
      if (files.length > 5) throw Exception("Exceed number of file upload");
      package.photoUrls = package.photoUrls == null ? [] : package.photoUrls;
      for (File f in files) {
        String path = Path.join(pkg_files_path);
        String url = await uploadStorage(path, f);
        package.photoUrls.add(url);
      }
    }
    await Services.instance.packageService.updateReceiving(package);
  }

  Future<void> deleteReceiving(Package package) {
    return Services.instance.packageService.deleteReceiving(package);
  }

  Future<void> updateProcessing(
      Package package, List<File> files, List<String> deletedUrls) async {
    if (deletedUrls != null) {
      for (String url in deletedUrls) {
        package.photoUrls.remove(url);
      }
      await deleteStorageFromUrls(deletedUrls);
    }

    if (files != null) {
      if (files.length > 5) throw Exception("Exceed number of file upload");
      package.photoUrls = package.photoUrls == null ? [] : package.photoUrls;
      for (File f in files) {
        String path = Path.join(pkg_files_path);
        String url = await uploadStorage(path, f);
        package.photoUrls.add(url);
      }
      package.photoUrls.removeWhere((e) => deletedUrls.contains(e));
    }
    await Services.instance.packageService.updateProcessing(package);
  }

  Future<void> deleteProcessing(Package package) {
    return Services.instance.packageService.deleteProcessing(package);
  }

  Future<void> changeDeliveryAddress(
      Package package, DeliveryAddress deliveryAddress) {
    return Services.instance.packageService
        .changeDeliveryAddress(package.id, deliveryAddress.id);
  }

  Future<void> packageReturn(Package package) {
    return Services.instance.packageService.packageReturn(package.id);
  }
}
