import 'package:agrilink_vocpro/core/state/result_state.dart';
import 'package:agrilink_vocpro/data/model/relay_response.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;

  bool _control_3 = false;
  bool get control_3 => _control_3;

  Relay _relay1 = Relay();
  Relay get relay1 => _relay1;

  Relay _relay2 = Relay();
  Relay get relay2 => _relay2;

  Relay _relay3 = Relay();
  Relay get relay3 => _relay3;

  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) {
            _relay1 = element;
            switchControl(element.currentStatus ?? false, relayNumber: 1);
          }
          if (element.number == 2) {
            _relay2 = element;
            switchControl(element.currentStatus ?? false, relayNumber: 2);
          }
          if (element.number == 3) {
            _relay3 = element;
            switchControl(element.currentStatus ?? false, relayNumber: 3);
          }
        }
        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 = state ? 1 : 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 switchControl(bool value, {required int relayNumber}) {
    switch (relayNumber) {
      case 1:
        _control_1 = value;
        break;
      case 2:
        _control_2 = value;
        break;
      case 3:
        _control_3 = value;
        break;
      default:
        return;
    }
    notifyListeners();
  }
}
