import 'package:dio/dio.dart'; import '../core/api_config.dart'; class ApiControlService { final Dio _dio; final String deviceId; ApiControlService(this.deviceId, [Dio? dio]) : _dio = dio ?? Dio(); // ── Mode Operasi ───────────────────────────────────────────── Future getMode() async { try { final res = await _dio.get('${ApiConfig.baseUrl}/mode/$deviceId'); if (res.statusCode == 200 && res.data != null) { return res.data['current_mode'] ?? 'auto'; } return 'auto'; } catch (e) { return 'auto'; } } Future setMode(String mode) async { try { await _dio.post( '${ApiConfig.baseUrl}/mode/$deviceId', data: {'mode': mode}, ); } catch (e) { throw Exception('Gagal mengubah mode: $e'); } } Future> getThreshold() async { try { final res = await _dio.get('${ApiConfig.baseUrl}/threshold/$deviceId'); if (res.statusCode == 200 && res.data != null) { return res.data; } throw Exception('Gagal memuat threshold'); } catch (e) { throw Exception('Error: $e'); } } Future updateThreshold(double tempMax, double humMax) async { try { await _dio.post( '${ApiConfig.baseUrl}/threshold/$deviceId', data: { 'temp_max': tempMax, 'hum_max': humMax, }, ); } catch (e) { throw Exception('Gagal update threshold: $e'); } } // ── Manual Control (Pompa) ─────────────────────────────────── Future siramManual(int durationSeconds) async { try { await _dio.post( '${ApiConfig.baseUrl}/schedule/$deviceId/now', data: {'duration_s': durationSeconds}, ); } catch (e) { throw Exception('Gagal menyalakan pompa: $e'); } } Future stopPump() async { try { await _dio.post('${ApiConfig.baseUrl}/schedule/$deviceId/stop'); } catch (e) { throw Exception('Gagal mematikan pompa: $e'); } } // ── Schedules (Jadwal) ─────────────────────────────────────── Future> getSchedules() async { try { final res = await _dio.get('${ApiConfig.baseUrl}/schedule/$deviceId'); if (res.statusCode == 200 && res.data != null) { return res.data as List; } return []; } catch (e) { throw Exception('Gagal memuat jadwal: $e'); } } Future> addSchedule(String cron, int durationSeconds, String label) async { try { final res = await _dio.post( '${ApiConfig.baseUrl}/schedule/$deviceId', data: { 'cron': cron, 'duration_s': durationSeconds, 'label': label, }, ); if (res.statusCode == 200 || res.statusCode == 201) { return res.data; } throw Exception('Gagal menambah jadwal'); } catch (e) { throw Exception('Error tambah jadwal: $e'); } } Future deleteSchedule(String id) async { try { await _dio.delete('${ApiConfig.baseUrl}/schedule/$id'); } catch (e) { throw Exception('Gagal menghapus jadwal: $e'); } } Future toggleSchedule(String id) async { try { await _dio.patch('${ApiConfig.baseUrl}/schedule/$id/toggle'); } catch (e) { throw Exception('Gagal toggle jadwal: $e'); } } }