import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/base/base_response_model.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import '../configs/callbacks.dart';
import '../configs/constants.dart';
import 'model_maker.dart';

enum Method {
  GET, POST, PUT
}

class RestfulAPIClient {
  final Dio _dio;
  RestfulAPIClient(this._dio);
  Json header = {};

  Future<BaseResponseModel<T>> requestNormal<T>(String path, Method method, Json params, CallbackReturn<T, dynamic> parser) async {
    final result = await request<BaseResponseModel<T>>(path, method, params, (data) {
      return BaseResponseModel<T>.fromJson(data, (json) => parser(json));
    });
    return result ?? BaseResponseModel<T>(errorMessage: Constants.commonError);
  }

  Future<T?> request<T>(String path, Method method, Json params, CallbackReturn<T, Json> parser) async {
    final isGet = method == Method.GET;
    Json query = isGet ? params : {};
    Json body = !isGet ? params : {};
    final option = Options(method: method.name)
            .compose(
          _dio.options,
          path,
          queryParameters: query,
          data: body,
        );
    String? token = await DataPreference.instance.token;
    if (token != null) {
      option.headers["Authorization"] = "Bearer $token";
    }
    try {
      final result = await _dio.fetch<Map<String, dynamic>>(option);
      final json = result.data;
      if (json == null) return null;
      return parser(json);
    } on DioException catch(e) {
      _print(e.toString());
      final data = e.response?.data;
      if (data is Json) {
        try {
          return parser(data);
        } catch (e) {
          _print(e.toString());
          return null;
        }
      } else {
        return null;
      }
    } catch(e) {
      _print(e.toString());
      return null;
    }
  }

  void _print(String error) {
    if (kDebugMode) {
      print("===================\nAPI Error Parse false ${error}\n================");
    }
  }
}