import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter_nsd/flutter_nsd.dart';
import 'package:get_it/get_it.dart';

import 'package:skillcourt/pad.dart';

final getIt = GetIt.instance;

class Station {
  String _name = '';
  late String _description = '';
  final List<Pad> _padList = <Pad>[];
  Offset? _playerLocation;
  bool get hasPads => _padList.isNotEmpty;
  String get description => _description;
  String get name => _name;
  Offset? get playerLocation => _playerLocation != null
      ? Offset(_playerLocation!.dx, _playerLocation!.dy)
      : null;

  int get padsCount => _padList.length;

  set playerLocation(Offset? ploc) {
    if (ploc == null) {
      _playerLocation = ploc;
    } else if (ploc.dx >= 0 && ploc.dy > 0) {
      _playerLocation = ploc;
    }
  }

  void setName(String name) {
    _name = name;
  }

  void setDescription(String description) {
    _description = description;
  }

  void addPad(Pad p) {
    _padList.add(p);
  }

  Pad? getPadWithIndex(int index) {
    if (index < 0 || index >= _padList.length) {
      return null;
    }
    return _padList.elementAt(index);
  }

  Pad? getPadWithNSI(NsdServiceInfo nsi) {
    for (final pad in _padList) {
      if (nsdServiceInfoEquals(pad.nsdServiceInfo, nsi)) {
        return pad;
      }
    }
    return null;
  }

  int? getPadIndexWithNSI(NsdServiceInfo nsi) {
    for (var i = 0; i < _padList.length; i++) {
      if (nsdServiceInfoEquals(_padList[i].nsdServiceInfo, nsi)) {
        return i;
      }
    }
    return null;
  }
}

bool nsdServiceInfoEquals(NsdServiceInfo nsi1, NsdServiceInfo nsi2) {
  return nsi1.hostname == nsi2.hostname &&
      nsi1.port == nsi2.port &&
      nsi1.name == nsi2.name &&
      mapEquals(nsi1.txt, nsi2.txt);
}
