import 'dart:async';
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:uco_mobile_poc/app/core/config/requset_attr.dart';
import 'package:uco_mobile_poc/app/core/config/server_response.dart';

import '../constants/translation_keys.dart';
import '../utils/logs_utils.dart';
import 'api_utils.dart';
import 'connectivity_service.dart';
import 'dio_exceptions.dart';
import 'logging.dart';

class ServerRequest {
  static Future<ServerResponse> request(RequestAttr requestAttr) async {
    /// Internet Connectivity Check
    if (!ConnectivityHelper.isNetworkConnected) {
      ServerResponse serverResponse = ServerResponse.init();
      serverResponse.isError = true;
      serverResponse.errorCode = "ERR_CONNECTION";
      serverResponse.errorMsg = TranslationKeys.makeTranslation(TranslationKeys.ERR_CONNECTION);
      return serverResponse;
    }

    _initRequest(requestAttr);

    try {
      dp("============request Before>>>> ", requestAttr.toString());

      final response = await _requestDio.request(
        requestAttr.url,
        options: Options(
          method: requestAttr.requestType.name,
          headers: requestAttr.headers,
        ),
        queryParameters: requestAttr.queryParams,
        data: requestAttr.body,
      );

      dp("============after Before>>>> ", response.toString());

      return ApiUtils.parseServerResponse(response);
    } on DioError catch (e) {
      ServerResponse response = DioExceptions.parseError(e);
      // if (response.statusCode == 401) {
      //   return refreshToken(requestAttr);
      // }
      pe("============catch Before>>>> ", e.toString());
      pe("Error responce", e.response);
      return DioExceptions.parseError(e);
    }
  }

  static late Dio _requestDio;
  static late BaseOptions _baseOptions;

  static void _initRequest(RequestAttr attr) {
    _baseOptions = BaseOptions(baseUrl: attr.url, connectTimeout: 15000, receiveTimeout: 90000);
    _baseOptions.contentType = Headers.jsonContentType;

    if (attr.headers.isNotEmpty) {
      _baseOptions.headers.addAll(attr.headers);
    }

    if (attr.queryParams.isNotEmpty) {
      _baseOptions.queryParameters.addAll(attr.queryParams);
    }

    _requestDio = Dio(_baseOptions);
    _requestDio.interceptors.add(Logging(attr));
    _requestDio.interceptors.add(InterceptorsWrapper(
      onResponse: (Response<dynamic> response, ResponseInterceptorHandler handler) {
        // Create a new response object without headers
        final newResponse = Response(
          requestOptions: response.requestOptions,
          data: response.data,
          statusCode: response.statusCode,
          statusMessage: response.statusMessage,
        );
        return handler.resolve(newResponse);
      },
    ));
    _requestDio.transformer = DefaultTransformer();

    (_requestDio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
      client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
      return client;
    };
  }

// static Future<ServerResponse> refreshToken(RequestAttr requestAttr) async {
//   RefreshTokenRequestModel userInfo = RefreshTokenRequestModel(
//     porOrgacode: SessionCache.instance.userInfo.porOrgacode,
//     pctCstycode: SessionCache.instance.userInfo.pctCstycode,
//     cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
//     cmpUserId: SessionCache.instance.userInfo.cmpUserId,
//     token: SessionCache.instance.userInfo.jwtToken,
//   );
//
//   Map<String, Object> headers = {};
//   headers["Authorization"] = "Bearer ${SessionCache.instance.userInfo.jwtToken}";
//   headers["Channelcode"] = SessionCache.instance.userInfo.channelCode;
//   headers["Cmpuserid"] = SessionCache.instance.userInfo.cmpUserId;
//   // headers["Devicename"] = "Mobile";
//
//   ServerResponse refreshTokenResponse = await ServerRequest.request(RequestAttr.withParamsAndBody(UrlContants.REFRESH_TOKEN, HttpMethod.POST, userInfo.toMap(), headers, {}));
//   String token = refreshTokenResponse.response["token"] ?? "";
//   if (token.isEmpty) {
//     Toasty.error("Session timeout, Signing out...");
//     Get.offAllNamed(Routes.LOGIN);
//     return ServerResponse.init();
//   }
//
//   SessionCache.instance.userInfo.jwtToken = token;
//   if (requestAttr.headers.containsKey("Authorization")) {
//     requestAttr.headers["Authorization"] = "Bearer ${SessionCache.instance.userInfo.jwtToken}";
//   }
//   return await ServerRequest.request(requestAttr);
// }
}
