import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'exception_interceptor.dart';
import 'logger_interceptor.dart';
import 'modify_request_interceptor.dart';

const int connectTimeout = 10; // seconds
const int receiveTimeout = 15; // second

class DioHttpService {
  static final DioHttpService _instance = DioHttpService._internal();

  late Dio _dio;
  String domain = '';

  factory DioHttpService() {
    return _instance;
  }

  void init() async {
    final Map<String, String> defaultHeaders = {'Accept': '*/*', 'Content-type': 'application/json'};

    // Set default configs
    _dio.options.connectTimeout = const Duration(seconds: connectTimeout); //10s
    _dio.options.receiveTimeout = const Duration(seconds: receiveTimeout);
    _dio.options.headers = defaultHeaders;
    _dio.interceptors.add(ModifyRequestInterceptor());
    if(kDebugMode) {
      _dio.interceptors.add(LoggerInterceptor());
    }
    _dio.interceptors.add(ExceptionInterceptor());
  }

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

  DioHttpService._internal() {
    // Initialize Dio instance with default configurations
    _dio = Dio(BaseOptions(
      baseUrl: domain,
      connectTimeout: Duration(seconds: connectTimeout),
      receiveTimeout: Duration(seconds: receiveTimeout),
    ));
  }

  Dio getDio() {
    return _dio;
  }
}