import 'dart:async';

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

const MANAGE_CARTONSIZE = "Manage Carton Size";

class CartonSizeModel extends BaseModel {
  List<CartonSize> cartonSizes = [];
  final log = Logger('CartonSizeModel');

  StreamSubscription<QuerySnapshot>? listener;

  List<CartonSize> get getCartonSizes {
    var _cartonSizes = new List<CartonSize>.from(cartonSizes);
    return _cartonSizes..insert(0, CartonSize(name: MANAGE_CARTONSIZE));
  }

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

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

      listener = FirebaseFirestore.instance
          .collection(
              "/$config_collection/$setting_doc_id/$carton_sizes_collection")
          .snapshots()
          .listen((QuerySnapshot snapshot) {
        cartonSizes.clear();
        cartonSizes = snapshot.docs.map((documentSnapshot) {
          var c = CartonSize.fromMap(
              documentSnapshot.data() as Map<String, dynamic>,
              documentSnapshot.id);
          return c;
        }).toList();
        notifyListeners();
      });
    } catch (e) {
      log.warning("Error!! $e");
    }
  }

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

  Future<void> addCartonSize(CartonSize cartonSize) async {
    await request("/carton_sizes", "POST",
        payload: cartonSize.toMap(), token: await getToken());
  }

  Future<void> updateCartonSize(CartonSize cartonSize) async {
    await request("/carton_sizes", "PUT",
        payload: cartonSize.toMap(), token: await getToken());
  }

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