import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:get/get.dart';

import 'package:google_sign_in/google_sign_in.dart';

class SocketTestController extends GetxController {
  Socket? socket;
  StreamSubscription? socketStreamSubscription;
  RxString message = ''.obs;

  // final GoogleSignIn googleSignIn =
  //     GoogleSignIn(scopes: ['https://www.googleapis.com/auth/drive.appdata']);
  // late GoogleSignInAccount? googleSignInAccount;

  @override
  void onInit() {
    super.onInit();
    //Loading, Success, Error handle with 1 line of code
    message.value += "OnInit finished ....\n\n";
  }

  @override
  void onClose() {
    super.onClose();
    disconnect();
    print("SocketTestController onClose ....");
  }

  void googleLogIn() async {
    // googleSignInAccount = await googleSignIn.signIn();

    // final GoogleSignInAuthentication googleSignInAuthentication =
    //     await googleSignInAccount!.authentication;

    // print("AccessToken: ${googleSignInAuthentication.accessToken}");
    // print("IdToken: ${googleSignInAuthentication.idToken}");
  }

  void connect() async {
    // socket = await Socket.connect(InternetAddress('3.23.52.207'), 2101,
    //     timeout: const Duration(seconds: 5));
    socket = await Socket.connect(InternetAddress('84.206.45.44'), 2101,
        timeout: const Duration(seconds: 5));
    socket?.asBroadcastStream;

    // socket?.encoding = ascii;
    print("Connect ....");
    message.value += "Connecting to caster .... \n\n";
    // message.value += _toBase64("info@mail.app-dev.hu:") + "\r\n";
    message.value += "${_toBase64("elgi08:Laszl0stef1")}\r\n";

    // String header = "GET /KOVARIK HTTP/1.1\r\n";
    String header = "GET /SGO_RTK3.2 HTTP/1.1\r\n";
    header += "User-Agent: SharpGps iter.dk\r\n";
    header += "Accept: */*\r\nConnection: close\r\n";
    // header += "Authorization: Basic ${_toBase64("info@mail.app-dev.hu:")}\r\n";
    header += "Authorization: Basic ${_toBase64("elgi08:Laszl0stef1")}\r\n";
    // header += "Host:rtk2go.com:2101\r\n";
    header += "Host:gnssnet.hu:2101\r\n";
    header += "Ntrip-Vesrsion:Ntrip/2.0\r\n";
    header += "\r\n";

    // listen for responses from the server
    socketStreamSubscription = socket?.listen(
      // handle data from the server
      (Uint8List data) {
        // "ICY 200 OK" - first response
        final serverResponse = String.fromCharCodes(data);
        int length = data.length;
        print('Server: $length');
      },

      // handle errors
      onError: (error) {
        print(error);
        socket?.destroy();
      },

      // handle server ending connection
      onDone: () {
        print('Server left.');
        socket?.destroy();
        socket = null;
      },
    );

    socket?.add(_convertStringToUint8List(header));
  }

  void disconnect() async {
    if (socket != null) {
      // socket?.close();
      socketStreamSubscription?.cancel();
      await socket?.flush();
      socket?.close();
      socket?.destroy();
      socket = null;
      print("Disconnect ....");
    }
  }

  String _toBase64(String str) {
    final bytes = ascii.encode(str);
    final base64Str = base64.encode(bytes);

    return base64Str;
  }

  Uint8List _convertStringToUint8List(String str) {
    final List<int> codeUnits = str.codeUnits;
    print("_convertStringToUint8List -> $codeUnits");
    print("length codeunits -> ${codeUnits.length}");
    print(
        "_convertStringToUint8List uint8list -> ${Uint8List.fromList(codeUnits)}");
    print(
        "_convertStringToUint8List uint8list length -> ${Uint8List.fromList(codeUnits).length}");
    final Uint8List unit8List = Uint8List.fromList(codeUnits);

    return unit8List;
  }

  String _convertUint8ListToString(Uint8List uint8list) {
    return String.fromCharCodes(uint8list);
  }
}
