// ignore_for_file: unnecessary_overrides
import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:IQ/app/modules/home/controllers/home_controller.dart';
import 'package:IQ/app/modules/selectISP/views/select_isp_view.dart';
import 'package:IQ/app/modules/service/api_service.dart';
import 'package:IQ/app/routes/app_pages.dart';
import 'package:IQ/main.dart';

class AutologinController extends GetxController with WidgetsBindingObserver {
  String errorText = '';

  reloadAutologin() async {
    errorText = '';
    update();
    var ispDetected = await detectISP();
    await makeOperationsAfterDetecting(ispDetected);
  }

  Future<String> detectISP() async {
    String str = "";
    try {
      http.Request response;
      response = http.Request(
        'GET',
        Uri.parse(
          'http://connect.snono-systems.com/index.php/api/fiberx/detect',
        ),
      );
      http.StreamedResponse request = await response.send();
      if (request.statusCode != 200) {
        storage.remove('token');
        // Get.offAllNamed(Routes.SELECT_I_S_P);
        return "${request.statusCode}";
      }
      String res = await request.stream.bytesToString();
      debugPrint("detectISP: $res");
      str = jsonDecode(res)["data"];
      return str;
    } catch (e) {
      if (e is SocketException) {
        str = "0";
        return str;
      } else if (e is TimeoutException) {
        str = "-2";
        return str;
      }
    }
    return str;
  }

  fetch() async {
    var value = await APIService.get(
      'auth/autoLogin?device_id=$deviceId&lat=$lat&long=$long',
      false,
    ).timeout(
      const Duration(seconds: 8),
      onTimeout: () {
        errorText = '';
        update();
      },
    );
    if (value == null) {
      errorText = 'autologin_failed_messageNull'.tr;
      update();
      return;
    }

    if (value.runtimeType == int) {
      if (value == 0) {
        errorText = 'autologin_failed_message0'.tr;
      }
      if (value == -2) {
        errorText = 'autologin_failed_message_2'.tr;
      }
      if (value == -1) {
        errorText = 'autologin_failed_message_1'.tr;
      }
      update();

      return;
    }
    var decodedValue = jsonDecode(value);
    if (decodedValue.toString().contains('token')) {
      token = decodedValue["token"];
      storage.write('token', token);
      Get.lazyPut<HomeController>(
        () => HomeController(),
      );
      Future.delayed(
        const Duration(seconds: 2),
        () {
          Get.offAllNamed(Routes.HOME);
        },
      );
    } else {
      errorText = value;
      Future.delayed(
        const Duration(seconds: 1),
        () {
          Get.offAllNamed(Routes.LOGIN);
        },
      );
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.inactive ||
        state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) return;
    if (state == AppLifecycleState.resumed) {
      defaultLocale = Platform.localeName.split('_')[0];
      textDirection =
          defaultLocale == "en" ? TextDirection.ltr : TextDirection.rtl;
    }
  }

  makeOperationsAfterDetecting(String ispDetected) async {
    if (ispDetected != "0" || ispDetected != "-2") {
      url = 'https://$ispDetected/user/api/index.php/api';
      liveDataUrl = 'http://$ispDetected/userlivetraffic/ucp/traffic?token=';
      storage.write('baseUrl', url);
      storage.write('liveDataUrl', liveDataUrl);
      fetch();
      debugPrint("#url: $url");
    } else {
      debugPrint("@url: $url");
      Future.delayed(const Duration(seconds: 2), () {
        Get.offAllNamed(Routes.LOGIN);
      });
    }
  }

  @override
  void onInit() async {
    super.onInit();
    var ispDetected = await detectISP();
    await makeOperationsAfterDetecting(ispDetected);
    return;
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
  }
}
