package com.vt.kakao.login;

import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import com.kakao.network.ErrorResult;

import java.net.HttpURLConnection;

public class KakaoCapacitorErrorHandler {
    public static void errorHandler(PluginCall callbackContext, ErrorResult errorResult){
        if(callbackContext == null){
            return;
        }
        try{
            JSObject errorJson =  new JSObject();
            errorJson.put("osType", "android");
            errorJson.put("errorCode", String.valueOf(errorResult.getErrorCode()));
            errorJson.put("errorMessage", String.valueOf(errorResult.getErrorMessage()));

            JSObject extraErrorJson =  new JSObject();
            extraErrorJson.put("httpStatus", String.valueOf(errorResult.getHttpStatus()));
            extraErrorJson.put("exception", (errorResult.getException() != null ? errorResult.getException().toString() : ""));

            errorJson.put("extra", extraErrorJson);


            callbackContext.error(errorJson.toString());
        }catch (Exception e){
            callbackContext.error("Something went wrong. " + e.toString());
        }
    }

    public static void errorHandler(PluginCall callbackContext, String errorMessage){
        if(callbackContext == null){
            return;
        }
        try{
            JSObject errorJson =  new JSObject();
            errorJson.put("osType", "android");
            errorJson.put("errorCode", String.valueOf(-777));
            errorJson.put("errorMessage", errorMessage);

            JSObject extraErrorJson =  new JSObject();
            extraErrorJson.put("httpStatus", HttpURLConnection.HTTP_INTERNAL_ERROR);
            extraErrorJson.put("exception", "");

            errorJson.put("extra", extraErrorJson);
            callbackContext.error(errorJson.toString());
        }catch (Exception e){
            callbackContext.error("Something went wrong. " + e.toString());
        }
    }

    public static void errorHandler(PluginCall callbackContext, int errorCode, String errorMessage){
        if(callbackContext == null){
            return;
        }
        try{
            JSObject errorJson =  new JSObject();
            errorJson.put("osType", "android");
            errorJson.put("errorCode", String.valueOf(errorCode));
            errorJson.put("errorMessage", errorMessage);
            JSObject extraErrorJson =  new JSObject();
            extraErrorJson.put("httpStatus", HttpURLConnection.HTTP_INTERNAL_ERROR);
            extraErrorJson.put("exception", "");

            errorJson.put("extra", extraErrorJson);
            callbackContext.error(errorJson.toString());
        }catch (Exception e){
            callbackContext.error("Something went wrong. " + e.toString());
        }
    }
}
