import 'dart:developer';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../authentication/bloc/authentication_bloc.dart';
import '../../common/const_enum.dart';
import '../../main.dart';
import '../../utils/local_storage.dart';

class DioProvider {
  static Dio dio = Dio();
  static Dio instance() {
    dio.options.baseUrl = 'https://tpf.aztrace.vn/';
    // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
    //   client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
    //   return client;
    // };
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          var token = LocalStorage.getString(LocalStorageKey.access_token);

          if (token.isNotEmpty) {
            options.headers['Authorization'] = 'Bearer $token';
          }
          options.headers['Content-Type'] = 'application/json';
          options.headers['accept'] = 'application/json';
          log('⭐⭐⭐⭐⭐⭐ onRequest: ${options.uri}\n'
              'data=${options.data}\n'
              'method=${options.method}\n'
              'headers=${options.headers}\n'
              'queryParameters=${options.queryParameters}');
          return handler.next(options);
        },
        onResponse: (response, handler) async {
          // log('🍏🍏🍏🍏🍏🍏 onResponse: $response');
          return handler.next(response);
        },
        onError: (DioError e, handler) async {
          log('🔥🔥🔥🔥🔥🔥 onError: $e\n'
              'Response: ${e.response}');
          handler.next(e);
        },
      ),
    );
    return dio;
  }

  static void logoutAndNavigationToSplashScreen() {
    LocalStorage.clearUserInfo();
    BlocProvider.of<AuthenticationBloc>(globalNavigator.currentContext!).add(
      const AuthenticationStatusChanged(
        AuthenticationStatus.unauthenticated,
      ),
    );
  }
}
