import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:proj4dart/proj4dart.dart' as proj4;

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

  late proj4.Projection eovProj;
  late proj4.Projection wgsProj;

  @override
  Future<void> onInit() async {
    super.onInit();

    final bytes = (await rootBundle.load('assets/Grids/etrs2eov_notowgs.gsb'))
        .buffer
        .asUint8List();

    proj4.Projection.nadgrid('Etrs2Eov', bytes);

    const def =
        '+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 '
        '+k_0=0.99993 +x_0=650000 +y_0=200000 +ellps=GRS67 '
        '+towgs84=52.17,-71.82,-14.9,0,0,0,0 '
        '+units=m +nadgrids=Etrs2Eov +no_defs';

    eovProj = proj4.Projection.add('EPSG:23700', def);
    wgsProj = proj4.Projection.WGS84;
  }

  Future<CoordConverterService> init() async {
    final bytes = (await rootBundle.load('assets/Grids/etrs2eov_notowgs.gsb'))
        .buffer
        .asUint8List();

    proj4.Projection.nadgrid('Etrs2Eov', bytes);

    const def =
        '+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 '
        '+k_0=0.99993 +x_0=650000 +y_0=200000 +ellps=GRS67 '
        '+towgs84=52.17,-71.82,-14.9,0,0,0,0 '
        '+units=m +nadgrids=Etrs2Eov +no_defs';

    eovProj = proj4.Projection.add('EPSG:23700', def);
    wgsProj = proj4.Projection.WGS84;

    return this; // ← ez a kulcs
  }

  // Segédmetódusok — nem kötelező, de tisztább
  proj4.Point wgsToEovPoint(double lon, double lat) =>
      wgsProj.transform(eovProj, proj4.Point(x: lon, y: lat));

  proj4.Point eovToWgsPoint(double y, double x) =>
      eovProj.transform(wgsProj, proj4.Point(x: y, y: x));
}
