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 '../dialogs/custom_loading.dart';
import '../utils/logs_utils.dart';
import 'api_utils.dart';

class Logging extends Interceptor {
  late RequestAttr requestAttr;

  Logging(this.requestAttr);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    showLoader();

    // refresh token if expired
    if (ApiUtils.isHeaderRequired) {
      // options.headers['Authorization'] = 'Bearer $API_KEY';
    }

    print(
        "request_data =>> TYPE: ${options.method}\n" + requestAttr.toString());

    return super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    hideLoader();
    print("Response_SUCCESS =>> ${response.data.toString()}");
    return super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    hideLoader();

    dp("============Error Response", err.response);

    if (err.response != null) {
      ServerResponse response = ServerResponse.init();

      ApiUtils.parseError(response, err.response!);

      pe("Response_ERROR =>> ", response.toString());
    } else {
      pe("DIO_ERROR =>> ", err.message);

      pe("ERROR_TYPE =>> ", err.type.toString());

      pe("STACKTRACE =>> ", err.error.toString());
    }

    return super.onError(err, handler);
  }
}
