package top.octopusyan.http.callback;

import javafx.application.Platform;
import okhttp3.Response;
import top.octopusyan.http.EasyUtils;
import top.octopusyan.http.HttpLog;
import top.octopusyan.http.api.RequestApi;
import top.octopusyan.http.listener.OnHttpListener;
import top.octopusyan.http.model.CallProxy;
import top.octopusyan.http.request.IRequestHandler;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description : 正常接口回调
 * @create : 2022-4-1 16:08
 */
public final class NormalCallback extends BaseCallback {

   private final OnHttpListener mListener;
   private final RequestApi mRequestApi;
   private final IRequestHandler mRequestHandler;

   public NormalCallback(CallProxy call, RequestApi api, IRequestHandler handler, OnHttpListener listener) {
      super(call);
      mRequestApi = api;
      mListener = listener;
      mRequestHandler = handler;

      EasyUtils.post(() -> {
         if (mListener == null) {
            return;
         }
         mListener.onStart(call);
      });
   }

   @SuppressWarnings("unchecked")
   @Override
   protected void onResponse(Response response) throws Exception {
      // 打印请求耗时时间
      HttpLog.print("RequestConsuming：" + (response.receivedResponseAtMillis() - response.sentRequestAtMillis()) + " ms");
      final Object result = mRequestHandler.requestSucceed(mRequestApi, response, mRequestHandler.getType(mListener));
      EasyUtils.post(() -> {
         if (mListener == null) {
            return;
         }
         mListener.onSucceed(result);
         mListener.onEnd(getCall());
      });
   }

   @Override
   protected void onFailure(Exception e) {
      final Exception exception = mRequestHandler.requestFail(mRequestApi, e);
      Platform.runLater(() -> HttpLog.print(exception));
      EasyUtils.post(() -> {
         mListener.onFail(exception);
         mListener.onEnd(getCall());
      });
   }
}
