package top.octopusyan.manager.http.callback;

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

/**
 * @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());
      });
   }
}
