import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/customer_exercise_device.dart';
import 'package:aitrainer_app/model/exercise_device.dart';
import 'package:aitrainer_app/model/model_change.dart';
import 'package:aitrainer_app/service/customer_exercise_device_service.dart';

class CustomerExerciseDeviceRepository {
  List<CustomerExerciseDevice> _devices = [];

  List<CustomerExerciseDevice> getDevices() => this._devices;

  void setDevices(List<CustomerExerciseDevice> devices) => this._devices = devices;

  Future<List<CustomerExerciseDevice>?> getDBDevices() async {
    if (Cache().userLoggedIn != null) {
      final int customerId = Cache().userLoggedIn!.customerId!;
      this._devices = await CustomerExerciseDeviceApi().getDevices(customerId);
    }
    return this._devices;
  }

  Future<void> addDevice(ExerciseDevice device) async {
    CustomerExerciseDevice? found;

    this._devices.forEach((element) {
      if (element.exerciseDeviceId == device.exerciseDeviceId) {
        found = element;
      }
    });

    if (found == null) {
      int? customerId;
      if (Cache().userLoggedIn != null) {
        customerId = Cache().userLoggedIn!.customerId!;
      }
      CustomerExerciseDevice newDevice =
          CustomerExerciseDevice(customerId: customerId!, exerciseDeviceId: device.exerciseDeviceId, favourite: false);
      newDevice.change = ModelChange.add;
      CustomerExerciseDevice saved = await CustomerExerciseDeviceApi().addDevice(newDevice);
      this._devices.add(saved);
      Cache().setCustomerDevices(_devices);
    }
  }

  Future<void> removeDevice(ExerciseDevice device) async {
    CustomerExerciseDevice? found;

    this._devices.forEach((element) {
      if (element.exerciseDeviceId == device.exerciseDeviceId) {
        found = element;
      }
    });

    if (found != null) {
      this._devices.remove(found);
      //if (found.change != ModelChange.add) {
      await CustomerExerciseDeviceApi().removeDevice(found!.customerExerciseDeviceId!);
      //}
      Cache().setCustomerDevices(_devices);
    }
  }

  bool hasDevice(int exerciseDeviceId) {
    bool found = false;

    this._devices.forEach((element) {
      if (element.exerciseDeviceId == exerciseDeviceId) {
        found = true;
      }
    });

    return found;
  }
}
