import 'dart:async';
import 'dart:io';
import 'package:fcs/data/services/services.dart';
import 'package:path/path.dart' as Path;

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

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

  StreamSubscription<QuerySnapshot> listener;
  List<Package> packages = [];

  @override
  void privilegeChanged() {
    super.privilegeChanged();
    _loadPackages();
  }

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

  Future<void> _loadPackages() async {
    if (user == null) return;
    String path = "";
    if (user.isCustomer()) {
      path = "/$user_collection/${user.id}/$packages_collection";
    } else {
      path = "/$packages_collection";
    }
    if (listener != null) listener.cancel();
    packages = [];

    try {
      listener = Firestore.instance
          .collection("$path")
          .where("is_delivered", isEqualTo: false)
          .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 = "";
    if (user.isCustomer()) {
      path = "/$user_collection/${user.id}/$packages_collection";
    } else {
      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<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> completeProcessing(
      Package package, List<File> files, List<String> deletedUrls) async {
    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, package.userID, package.id);
        String url = await uploadStorage(path, f);
        package.photoUrls.add(url);
      }
      package.photoUrls.removeWhere((e) => deletedUrls.contains(e));
    }
    await request("/packages", "PUT",
        payload: package.toJson(), token: await getToken());
  }

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