package com.dbs.mplus.fatima.consent;

import android.content.Context;
import android.webkit.WebView;

import com.dbs.mplus.fatima.framework.util.MPlusLogUtil;
import com.dbs.mplus.fatima.framework.util.MPlusStringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import kr.co.clipsoft.eform.event.ExitEventArgs;
import kr.co.clipsoft.eform.event.IEventHandler;

/**
 * 앱 종료시 발생되는 이벤트 핸들러
 */
class EFormExitHandler implements IEventHandler<ExitEventArgs> {

    private String callbackFunction;

    private final WebView webView;

    public EFormExitHandler(WebView webView, String callbackFunction) {
        this.webView = webView;
        this.callbackFunction = callbackFunction;
    }

    @Override
    public void eventReceived(Object sender, ExitEventArgs e) {
        JSONObject result = new JSONObject();
        JSONObject resultCode = new JSONObject();
        switch(e.getResultCode()) {
            // 정상 종료
            case EXIT:
                try {
                    resultCode.put("resultCode", 200);
                    result.put("result", resultCode);
                } catch (JSONException e1) {
                    // 발생안함
                    e1.printStackTrace();
                }
                this.webView.loadUrl(MPlusStringUtil.getCallbackFnString(callbackFunction, result.toString()));
                MPlusLogUtil.DEBUG(this.getClass(), "정상 종료");
                break;
            // 비정상 종료
            case ERROR_EXIT:
                try {
                    resultCode.put("resultCode", 100);
                    result.put("result", resultCode);
                } catch (JSONException e1) {
                    // 발생안함
                    e1.printStackTrace();
                }
                String errorMessage = e.getErrorMessage();
                MPlusLogUtil.DEBUG(this.getClass(), "비정상 종료:" + errorMessage);
                this.webView.loadUrl(MPlusStringUtil.getCallbackFnString(callbackFunction, result.toString()));
                break;
        }
    }
}