package com.dbs.mplus.fatima.view.popup;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.dbs.mplus.fatima.MPlusConstants;
import com.dbs.mplus.fatima.framework.MPlusFrameworkConstants;
import com.dbs.mplus.fatima.framework.util.MPlusDeviceUtil;
import com.dbs.mplus.fatima.framework.util.MPlusLogUtil;
import com.dbs.mplus.fatima.framework.util.MPlusStringUtil;
import com.dbs.mplus.fatima.framework.view.dialog.MPlusDialog;
import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.util.IntentUtil;
import com.dbs.mplus.fatima.view.web.MPlusWebChromeClient;

import java.net.URISyntaxException;

/**
 * 병원과의 인터페이스를 처리하는 기본 웹뷰가 아닌 추가화면
 * 사용처 :  결제연동, 의약품백과사전 연동
 */
public class MPlusWebExtraPopupActivity extends Activity {
    private WebView webView;
//    private String callBackFnName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.activity_mcare_web_extra_popup);

        // 실행정보 가져와서
        final Bundle bundle = this.getIntent().getExtras();
        // 무엇을 처리해야 하는지 꺼내고
        String action = bundle.getString(MPlusConstants.ACTION_KEY);

        // 브라우징
        if (MPlusConstants.ACTION_EXTRA_POPUP_BROWSING.equals(action)) {
            this.processBrowsing(bundle);
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch(keyCode) {
            case KeyEvent.KEYCODE_HOME : // system에서 override되서 폰의 홈 화면으로 이동됨
                return true;

            case KeyEvent.KEYCODE_BACK : // 화면마다 back이 달라서 무시함
                if(this.webView != null) {
                    this.webView.loadUrl("javascript:triggerBackBtn();");
                }
                return true;

            case KeyEvent.KEYCODE_MENU :
                // 무시
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 브라우징 처리
     * @param bundle
     */
    private void processBrowsing(final Bundle bundle) {
        // 보여줄 URL 꺼내고
        final String url = bundle.getString(MPlusFrameworkConstants.MSG_VALUE_KEY.BROWSING_URL.toString());

        // 필요한 객체 만들기
        if (this.webView == null) {
            this.initComponent(null, null);
        }

        if (MPlusStringUtil.isEmpty(url)) {
            MPlusLogUtil.ERROR(MPlusWebExtraPopupActivity.class, "불완전한 메시지 : " + IntentUtil.getIntentString(this.getIntent()));
            this.finish();
            return;
        }
    }

    /**
     * 객체 초기화
     * @param paymentReqUrl 요청 보낼 URL
     */
    private void initComponent(final String paymentReqUrl, String callBackFnName) {
        // webView
        this.webView = (WebView) this.findViewById(R.id.webExtraPopupView);
        if(paymentReqUrl == null) {
            // 일반 브라우징용
            this.webView.setWebViewClient(new MCareWebExtraPopupViewClient());
        }
        else {
            // 결제 연동용
            this.webView.setWebViewClient(new MCarePaymentPopupViewClient());
        }


        final WebSettings settings = this.webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setSaveFormData(true);
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        settings.setSupportMultipleWindows(false);
        // uuid 붙여주기
        settings.setUserAgentString(settings.getUserAgentString() + " " + MPlusConstants.USER_AGENT_UUID_STR + MPlusDeviceUtil.getDeviceUUID(this.getApplicationContext()));

        // 안 필요할것 같은데...
        //this.webView.addJavascriptInterface(new MPlusWebProcessor(this, this.webView), MPlusConstants.WEB_JAVASCRIPT_INF_NAME);

        //
        final ProgressBar pb = (ProgressBar) this.findViewById(R.id.webExtraPopupPB);
        /**
         * 인증창에서 취소가 발생할때 호출된다고 한다.
         */
        this.webView.setWebChromeClient(new MPlusWebChromeClient(this.getApplicationContext(), pb) {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                final JsResult resultParam = result;
                //
                AlertDialog dlg = MPlusDialog.getOKDialog(view.getContext(), "", message, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        resultParam.confirm();
                    }
                });

                dlg.setCancelable(false);
                dlg.show();

                return true;
            }

            @Override
            public void onCloseWindow(WebView webView) {
                super.onCloseWindow(webView);

                // 로그로 확인
                MPlusLogUtil.DEBUG(MPlusWebExtraPopupActivity.class, "onCloseWindow 이벤트 발생");
                // 결제요청 페이지 URL을 기입하라고 되어 있음
                if (paymentReqUrl != null) {
                    webView.postUrl(paymentReqUrl, null);
                }

            }
        });


        // close
        final ImageButton closeBtn = (ImageButton) this.findViewById(R.id.webExtraPopUpCloseBtn);
        closeBtn.setOnClickListener(new PopupCloseButtonClickListener(callBackFnName));
    }

    /**
     * 닫힘버튼 처리
     */
    class PopupCloseButtonClickListener implements View.OnClickListener {
        private final String callBackFnName;

        /**
         * 생성자
         * @param callBackFnName
         */
        public PopupCloseButtonClickListener(String callBackFnName) {
            this.callBackFnName = callBackFnName;
        }

        @Override
        public void onClick(View view) {
            // 콜백 함수명 전달할 수 있게 구조 잡아주고
            Intent intent = new Intent();
            intent.putExtra(MPlusFrameworkConstants.MSG_VALUE_KEY.CALLBACK_FN.toString(), callBackFnName);
            // 결과 심어주고
            MPlusWebExtraPopupActivity.this.setResult(Activity.RESULT_OK, intent);
            // 현재화면은 종료
            MPlusWebExtraPopupActivity.this.finish();
        }
    }

    /**
     * 웹 메시지 처리
     */
    class MCareWebExtraPopupViewClient extends WebViewClient {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Build.VERSION.SDK_INT < 21) {
                CookieSyncManager.getInstance().sync();
            }

            view.loadUrl(url);
            MPlusLogUtil.DEBUG(this.getClass(), "shouldOverrideUrlLoading, url : " + url);

            return false;
        }
    }

    /**
     * 결제용 처리
     */
    class MCarePaymentPopupViewClient extends WebViewClient {


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            // NicePay 화면에서 SSG로 넘어갈때 이런 intent가 날아다님
            // intent://externalpayment?reqId=xxx#Intent;scheme=shinsegaeeasypayment;package=com.ssg.serviceapp.android.egiftcertificate;end;
            if(url != null && url.startsWith("intent")) {
                Intent intent = null;

                // scheme 분석
                try {
                    intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                }
                catch(URISyntaxException ex) {
                    MPlusLogUtil.ERROR(MCarePaymentPopupViewClient.class, "url : " + url);
                    return false;
                }

                // 설치되지 않았으면 마켓으로 이동
                if(getPackageManager().resolveActivity(intent, 0) == null) {
                    String packageName = intent.getPackage();
                    if(packageName != null) {
                        startActivity(IntentUtil.getOpenMarketIntent("market://search?q=pname:" + packageName));
                        return true;
                    }
                }
                else {
                    startActivity(IntentUtil.getOpenUri(Uri.parse(intent.getDataString())));
                    return true;
                }
            }

            return false;
        }
    }
}
