import 'dart:async';

import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:voice_buddies/app/widget/base_controller.dart';

import '../../../models/login_model.dart';
import '../../../utils/all_imports.dart';

class SplashController extends BaseController {
  @override
  Future<void> onInit() async {
    socketMethod();

    Timer(
      const Duration(seconds: 3),
      () async {
        if (getStorageData.containKey(getStorageData.loginData)) {
          loginData = LoginData.fromJson(await getStorageData.readObject(getStorageData.loginData));
          if (loginData != null) {
            Get.offAllNamed(Routes.BOTTOM_BAR);
          } else {
            Get.offAllNamed(Routes.LOGIN);
          }
        } else {
          Get.offAllNamed(Routes.LOGIN);
        }
      },
    );

    super.onInit();
  }

  socketMethod() async {
    await getUserData();
    await socketRegister();
  }

  socketRegister() {
    Constants.socket = IO.io(
      Constants.socketBaseUrl,
      <String, dynamic>{
        'transports': ['websocket'],
        'upgraded': ['websocket'],
        'autoConnect': true,
      },
    );
    // TODO : Socket Connections Methods

    // TODO : on Connect
    Constants.socket!.onConnect((data) => checkSocket(data, "onConnect"));

    // TODO : on Connecting
    Constants.socket!.onConnecting((data) => checkSocket(data, "onConnecting"));

    // TODO : on ConnectError
    Constants.socket!.onConnectError((data) => checkSocket(data, "onConnectError"));

    // TODO : on Connect Timeout
    Constants.socket!.onConnectTimeout((data) => checkSocket(data, "onConnectTimeout"));

    // TODO : on Disconnect
    Constants.socket!.onDisconnect((data) => checkSocket(data, "onDisconnect"));
  }

  void checkSocket(data, String identify) {
    if (identify == 'onConnect') {
      printOkStatus(" <<< ---------- Socket $identify ---------- >>>");
    } else {
      printError(" <<< ---------- Socket $identify ---------- >>>");
    }
  }
}
