import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'interceptor/auth_interceptor.dart';
import 'interceptor/exception_interceptor.dart';
import 'interceptor/logger_interceptor.dart';
import 'interceptor/request_interceptor.dart';

const int connectTimeout = 30;
const int receiveTimeout = 30;

class DioHttpService {
  DioHttpService._internal();
  static final DioHttpService _instance = DioHttpService._internal();
  factory DioHttpService() => _instance;
  String _baseUrl = '';
  Dio get dio => _dio;

  late final Dio _dio =
      Dio(
          BaseOptions(
            baseUrl: _baseUrl,
            connectTimeout: const Duration(seconds: connectTimeout),
            receiveTimeout: const Duration(seconds: receiveTimeout),
            contentType: 'application/json',
            responseType: ResponseType.json,
            validateStatus: (_) => true,
            receiveDataWhenStatusError: true,
          ),
        )
        ..interceptors.add(RequestInterceptor())
        ..interceptors.addAll(kReleaseMode ? const [] : [LoggerInterceptor()])
        ..interceptors.add(AuthInterceptor())
        ..interceptors.add(ExceptionInterceptor());
        // ..interceptors.add(
        //   InterceptorsWrapper(
        //     onError: (e, h) {
        //       if (e.response != null) return h.resolve(e.response!);
        //       h.next(e);
        //     },
        //   ),
        // );

  void setBaseUrl(String newUrl) {
    _baseUrl = newUrl;
    _dio.options.baseUrl = newUrl;
  }

  void setDefaultHeaders(Map<String, dynamic> headers) {
    dio.options.headers.addAll(headers);
  }
}