import 'package:agrilink_vocpro/core/state/result_state.dart';
import 'package:agrilink_vocpro/domain/service/app_service.dart';
import 'package:flutter/foundation.dart';

class ControlProvider extends ChangeNotifier {
  final AppService _appService = AppService();

  bool _control_1 = false;
  bool get control_1 => _control_1;

  bool _control_2 = false;
  bool get control_2 => _control_2;

  ControlProvider() {
    getRelayStatus();
  }

  ResultState relayState = ResultState.initial;

  Future<void> getRelayStatus() async {
    relayState = ResultState.loading;
    notifyListeners();
    try {
      if (kDebugMode) {
        print('try to get relay status...');
      }
      final result = await _appService.getRelayStatus();
      if (result.success == true) {
        for (var element in result.data!) {
          if (element.number == 1) {
            switchControl1(element.currentStatus ?? false);
          }
          if (element.number == 2) {
            switchControl2(element.currentStatus ?? false);
          }
        }
        relayState = ResultState.hasData;
        notifyListeners();
      } else {
        relayState = ResultState.error;
        notifyListeners();
      }
    } catch (e) {
      relayState = ResultState.error;
      notifyListeners();
      if (kDebugMode) {
        print('Error Getting Relay Status: $e');
      }
    }
  }

  Future<bool> switchRelay(int relayNumber, bool state) async {
    relayState = ResultState.loading;
    notifyListeners();

    final int stateConverted;
    if (state == true) {
      stateConverted = 1;
    } else {
      stateConverted = 0;
    }
    try {
      final result = await _appService.switchRelay(
          relayNumber: relayNumber, state: stateConverted);
      if (result.success == true) {
        relayState = ResultState.hasData;
        notifyListeners();
        if (kDebugMode) {
          print(result.message);
        }
        return true;
      } else {
        return false;
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
      relayState = ResultState.error;
      notifyListeners();
      return false;
    }
  }

  void switchControl1(bool value) {
    _control_1 = value;
    notifyListeners();
  }

  void switchControl2(bool value) {
    _control_2 = value;
    notifyListeners();
  }
}
