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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.dbs.mplus.fatima.framework.MPlusFrameworkConstants;
import com.dbs.mplus.fatima.framework.util.MPlusDeviceUtil;

/**
 * @author hyeeun 
 */
public class MPlusWebViewWrapper {
    private final Activity activity;
    private final ProgressBar webViewPB;
    private final WebView webView;
    private MPlusWebViewClient webViewClient;

    /**
     * 생성자
     * @param activity
     * @param webViewPB
     * @param webView
     */
    public MPlusWebViewWrapper(Activity activity, ProgressBar webViewPB, WebView webView) {
        this.activity = activity;
        this.webViewPB = webViewPB;
        this.webView = webView;
    }

    /**
     * 초기화
     */
	@SuppressWarnings("deprecation")
    @SuppressLint("SetJavaScriptEnabled")
	public void init() {
        // java script 동작할 수 있도록
        final WebSettings webViewSettings = this.webView.getSettings();
        webViewSettings.setJavaScriptEnabled(true);
        this.webView.addJavascriptInterface(new MPlusWebProcessor(this.activity, this.webView), MPlusFrameworkConstants.WEB_JAVASCRIPT_INF_NAME);
        // local storage 사용
        webViewSettings.setDomStorageEnabled(true);
        // 파일 접근할 수 있도록 설정
        webViewSettings.setAllowFileAccess(true);
        // uuid 붙여주기 
        webViewSettings.setUserAgentString(webViewSettings.getUserAgentString() + " " + MPlusFrameworkConstants.USER_AGENT_UUID_STR + MPlusDeviceUtil.getDeviceUUID(this.activity.getApplicationContext()));
        // 웹 뷰에 맞게 출력하기...효과없다. 다음에 또 실험할까봐 남겨둠.
        //webViewSettings.setLoadWithOverviewMode(true);
        //webViewSettings.setUseWideViewPort(true);

        // 줌인 사용
        webViewSettings.setSupportZoom(true);
        webViewSettings.setBuiltInZoomControls(true);

        webViewSettings.setSupportMultipleWindows(true); // a target="_blank" 처리를 위함

        //
        this.webViewClient = new MPlusWebViewClient(this.activity);
        //
        this.webView.setWebViewClient(this.webViewClient);
        this.webView.setWebChromeClient(new MPlusWebChromeClient(this.activity.getApplicationContext(), this.webViewPB));
        this.webView.clearCache(true);
        
        
        if(MPlusFrameworkConstants.DEBUG_MODE && android.os.Build.VERSION.SDK_INT >= 19) {
        	// 19버전 이상에서 지원 
        	WebView.setWebContentsDebuggingEnabled(true); 
        } 
        
//        // 인터넷에 돌아다니는.. WebView 성능이 좀 떨어진다는 이야기에 이렇게 해보라고 제시된 코드 
//        // 체감 할려면 좀 더 실험해봐야할 듯 
//        if (android.os.Build.VERSION.SDK_INT >= 19) {
//            this.webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
//        }       
//        else {
//        	try { 
//        		this.webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//        	}
//        	catch(NoSuchMethodError er) { 
//        		MPlusLogUtil.DEBUG(this.getClass(), "webView.setLayerType 없음. 무시.");
//        	}
//        }
//


        CookieSyncManager.createInstance(this.activity.getApplicationContext()); 
        
        //쿠키허용 
//      if (android.os.Build.VERSION.SDK_INT >= 21) {
//      	CookieManager.getInstance().setAcceptThirdPartyCookies(true);
//      }
//      else {
      		CookieManager.getInstance().setAcceptCookie(true); 
//      }        
        
        // CookieSyncManager
        // This class was deprecated in API level 21.
        // The WebView now automatically syncs cookies as necessary. You no longer need to create or use the CookieSyncManager.
        if(android.os.Build.VERSION.SDK_INT < 21) {
        	 CookieSyncManager.createInstance(this.activity.getApplicationContext());
        	 CookieSyncManager.getInstance().startSync();
        }
        CookieManager.getInstance().setAcceptCookie(true);
    }

    /**
     * 로딩한 페이지 URL 반환 
     * @return
     */
    public String getPageUrl() { 
    	return this.webViewClient.getPageUrl(); 
    }
    
    /**
     * @see WebView
     * @param url
     */
    @SuppressWarnings("deprecation")
	public void loadUrl(String url) {
    	// 페이지 로딩 
    	//MPlusLogUtil.DEBUG(MPlusWebViewWrapper.class, "url : " + url);
        this.webView.loadUrl(url);

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