import 'dart:convert';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../model/filament_model.dart';

class FilamentRepository extends GetxService {
  static FilamentRepository get to => Get.find();

  final GetStorage _storage = GetStorage();
  static const String _storageKey = 'filaments';

  Future<FilamentRepository> init() async {
    await GetStorage.init();
    return this;
  }

  // Create - Füge ein neues Filament hinzu
  Future<bool> createFilament(FilamentModel filament) async {
    try {
      final filaments = getAllFilaments();
      filaments.add(filament);
      await _storage.write(
        _storageKey,
        filaments.map((f) => f.toJson()).toList(),
      );
      return true;
    } catch (e) {
      print('Error creating filament: $e');
      return false;
    }
  }

  // Read - Alle Filamente abrufen
  List<FilamentModel> getAllFilaments() {
    try {
      final data = _storage.read(_storageKey);
      //Wenn nichts gespeichert ist, gebe die Mockup Liste zurück
      if (data == null) return FilamentModel.mockupFilamentList;

      return (data as List)
          .map((json) => FilamentModel.fromJson(json))
          .toList();
    } catch (e) {
      print('Error reading filaments: $e');
      // Bei Fehlerfall gebe die Mockup Liste zurück
      return FilamentModel.mockupFilamentList;
    }
  }

  // Read - Einzelnes Filament nach ID
  FilamentModel? getFilamentById(String id) {
    try {
      final filaments = getAllFilaments();
      return filaments.firstWhereOrNull((f) => f.id == id);
    } catch (e) {
      print('Error getting filament by id: $e');
      return null;
    }
  }

  // Update - Aktualisiere ein Filament
  Future<bool> updateFilament(FilamentModel filament) async {
    try {
      final filaments = getAllFilaments();
      final index = filaments.indexWhere((f) => f.id == filament.id);

      if (index == -1) return false;

      filaments[index] = filament;
      await _storage.write(
        _storageKey,
        filaments.map((f) => f.toJson()).toList(),
      );
      return true;
    } catch (e) {
      print('Error updating filament: $e');
      return false;
    }
  }

  // Delete - Lösche ein Filament
  Future<bool> deleteFilament(String id) async {
    try {
      final filaments = getAllFilaments();
      filaments.removeWhere((f) => f.id == id);
      await _storage.write(
        _storageKey,
        filaments.map((f) => f.toJson()).toList(),
      );
      return true;
    } catch (e) {
      print('Error deleting filament: $e');
      return false;
    }
  }

  // Delete All - Lösche alle Filamente
  Future<bool> deleteAllFilaments() async {
    try {
      await _storage.remove(_storageKey);
      return true;
    } catch (e) {
      print('Error deleting all filaments: $e');
      return false;
    }
  }

  // Backup - Exportiere als JSON String
  String exportToJson() {
    try {
      final filaments = getAllFilaments();
      return jsonEncode(filaments.map((f) => f.toJson()).toList());
    } catch (e) {
      print('Error exporting to JSON: $e');
      return '[]';
    }
  }

  // Restore - Importiere von JSON String
  Future<bool> importFromJson(String jsonString) async {
    try {
      final List<dynamic> data = jsonDecode(jsonString);
      final filaments = data
          .map((json) => FilamentModel.fromJson(json))
          .toList();
      await _storage.write(
        _storageKey,
        filaments.map((f) => f.toJson()).toList(),
      );
      return true;
    } catch (e) {
      print('Error importing from JSON: $e');
      return false;
    }
  }

  // Zähle alle Filamente
  int getCount() {
    return getAllFilaments().length;
  }

  // Suche Filamente nach Name
  List<FilamentModel> searchByName(String query) {
    final filaments = getAllFilaments();
    return filaments
        .where((f) => f.name.toLowerCase().contains(query.toLowerCase()))
        .toList();
  }

  // Filtere nach Typ (z.B. PLA, ABS, PETG)
  List<FilamentModel> filterByType(String type) {
    final filaments = getAllFilaments();
    return filaments.where((f) => f.type == type).toList();
  }
}
