import 'package:hive/hive.dart';

part 'sector_model.g.dart';

@HiveType(typeId: 3)
class SectorModel extends HiveObject {
  @HiveField(0)
  final int id;

  @HiveField(1)
  final String libelle;

  @HiveField(2)
  final String color;

  @HiveField(3)
  final String sector;

  SectorModel({
    required this.id,
    required this.libelle,
    required this.color,
    required this.sector,
  });

  // Factory pour convertir depuis JSON (API)
  factory SectorModel.fromJson(Map<String, dynamic> json) {
    return SectorModel(
      id: json['id'] is String ? int.parse(json['id']) : json['id'] as int,
      libelle: json['libelle'] as String,
      color: json['color'] as String,
      sector: json['sector'] as String,
    );
  }

  // Convertir en JSON pour l'API
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'libelle': libelle,
      'color': color,
      'sector': sector,
    };
  }

  // Copier avec de nouvelles valeurs
  SectorModel copyWith({
    int? id,
    String? libelle,
    String? color,
    String? sector,
  }) {
    return SectorModel(
      id: id ?? this.id,
      libelle: libelle ?? this.libelle,
      color: color ?? this.color,
      sector: sector ?? this.sector,
    );
  }

  // Obtenir les coordonnées du secteur sous forme de liste de points
  List<List<double>> getCoordinates() {
    final List<List<double>> coordinates = [];
    
    // Le format est "lat1/lng1#lat2/lng2#lat3/lng3#..."
    final List<String> points = sector.split('#');
    
    for (final String point in points) {
      if (point.isEmpty) continue;
      
      final List<String> latLng = point.split('/');
      if (latLng.length == 2) {
        try {
          final double lat = double.parse(latLng[0]);
          final double lng = double.parse(latLng[1]);
          coordinates.add([lat, lng]);
        } catch (e) {
          // Ignorer les points mal formatés
        }
      }
    }
    
    return coordinates;
  }
}
