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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
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.util.MPlusDeviceUtil;
import com.dbs.mplus.fatima.framework.util.MPlusLogUtil;
import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.util.IntentUtil;
import com.dbs.mplus.fatima.view.web.MPlusWebChromeClient;
import com.dbs.mplus.fatima.view.web.MPlusWebProcessor;

import java.util.Iterator;


/**
 * 사용자 인증 처리를 위한 WebView를 가지는 팝업
 * @author hyeeun 
 *
 */
@SuppressLint("SetJavaScriptEnabled")
public class MPlusWebAuthPopupActivity extends Activity {
    private WebView webView;

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

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

        MPlusLogUtil.DEBUG(this.getClass(), "onCreate");


//        // 배경 약간 뿌옇게
//        final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
//        layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
//        layoutParams.dimAmount = 0.6f;
//        this.getWindow().setAttributes(layoutParams);


        // 필요한 객체 만들기
        if(this.webView == null) {
            // webView
            this.webView = (WebView) this.findViewById(R.id.webPopupView);
            this.webView.setWebViewClient(new MCareWebPopupViewClient());
            final WebSettings settings = this.webView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setSupportMultipleWindows(true);
            settings.setSaveFormData(true);
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            // 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.webPopupPB);
            this.webView.setWebChromeClient(new MPlusWebChromeClient(this.getApplicationContext(), pb));

            // close
            final ImageButton closeBtn = (ImageButton) this.findViewById(R.id.webPopupCloseBtn);
            closeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MPlusWebAuthPopupActivity.this.finish();
                }
            });
        }



        // intent 가져와서
        final Intent intent = this.getIntent();
        final Bundle bundle = intent.getExtras();

        MPlusLogUtil.DEBUG(this.getClass(), IntentUtil.getIntentString(intent));

        // post로 webView 띄우는거..
        // 휴대폰 본인인증, i-Pin 본인인증
        if(MPlusConstants.ACTION_AUTH_POPUP_BROWSING.equals(bundle.getString(MPlusConstants.ACTION_KEY))) {
            // 파라미터 정리
            final StringBuilder builder = new StringBuilder();

            final Iterator<String> keyIter = bundle.keySet().iterator();
            String key = null;

            while(keyIter.hasNext()) {
                key = keyIter.next();

                builder.append(key).append("=").append(bundle.getString(key)).append("&");
            }

            // url
            final String url = bundle.getString(MPlusConstants.MSG_VALUE_KEY.BROWSING_URL.toString());

            this.webView.loadUrl(url);
            if(android.os.Build.VERSION.SDK_INT < 21) {
                CookieSyncManager.getInstance().sync();
            }
        }
    }


    class MCareWebPopupViewClient extends WebViewClient {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(android.os.Build.VERSION.SDK_INT < 21) {
                CookieSyncManager.getInstance().sync();
            }

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

            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            MPlusLogUtil.DEBUG(this.getClass(), "onPageStarted. url : " + url);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            MPlusLogUtil.DEBUG(this.getClass(), "onPageFinished. url : " + url);
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
            MPlusLogUtil.DEBUG(this.getClass(), "host : " + host);
            super.onReceivedHttpAuthRequest(view, handler, host, realm);
        }
    }
}
