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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.dbs.mplus.fatima.framework.util.MPlusLogUtil;
import com.dbs.mplus.fatima.framework.util.MPlusResourceUtil;
import com.dbs.mplus.fatima.framework.util.MPlusServiceUtil;
import com.dbs.mplus.fatima.framework.util.MPlusWebErrorUtil;
import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.util.AddrUtil;
import com.dbs.mplus.fatima.util.IntentUtil;

/**
 * 
 * @author hyeeun 
 *
 */
@SuppressWarnings("deprecation")
public class MPlusWebViewClient extends WebViewClient {
	private final Activity activity; 
	private final String helperUrl; 
	private String pageUrl; 
	
	/**
	 * 생성자 
	 * @param activity
	 */
	public MPlusWebViewClient(Activity activity) {
		this.activity = activity; 
		this.pageUrl = null; 
		this.helperUrl = AddrUtil.getHelperPage(); 
	}
	/**
	 * 로딩 시작한 페이지 URL 
	 * @return
	 */
	public String getPageUrl() { 
		return this.pageUrl; 
	}
	
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // 여기서도 쿠키 동기화가 필요 
    	if(android.os.Build.VERSION.SDK_INT < 21) {
        	final CookieSyncManager syncManager = CookieSyncManager.getInstance();
        	syncManager.sync();
    	}

    	// http는 웹뷰에게 맡기고 
    	if(url.startsWith("https://") || url.startsWith("http://")) {
    		return false; 
    	}
    	
    	// 전화를 연결해주기 위함 
		if(url.startsWith(WebView.SCHEME_TEL)) {
			final Intent intent = IntentUtil.getPhoneCallIntent(url);
			this.activity.startActivity(intent);
			return true;
		}

		// 메일연결
		if(url.startsWith(WebView.SCHEME_MAILTO)) {
			final Intent intent = IntentUtil.getMailSendIntent(url);
			this.activity.startActivity(intent);
			return true;
		}

        return false;
    }
    
    
    
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		MPlusLogUtil.DEBUG(this.getClass(), "onPageStarted. url : " + url);
		
		super.onPageStarted(view, url, favicon); 
		// 백업 
		this.pageUrl = url; 
		
		// progressBar 보이게 
		final ProgressBar pb = (ProgressBar) this.activity.findViewById(R.id.webViewPB); 
		pb.setVisibility(View.VISIBLE);
		
        // 도우미 화면으로 갔는지 검사 
        if(url.startsWith(this.helperUrl)) {
        	// 알림바에 들어온거 삭제 
         	MPlusServiceUtil.cancelAllNotification(this.activity.getApplicationContext());
        }		
	}

	@Override
	public void onPageFinished(WebView view, String url) { 
		MPlusLogUtil.DEBUG(this.getClass(), "onPageFinished. url : " + url);
		super.onPageFinished(view, url);
		
		// progressBar 안 보이게 
		final ProgressBar pb = (ProgressBar) this.activity.findViewById(R.id.webViewPB); 
		pb.setVisibility(View.GONE);	

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


    @Override 
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // 23버전에서는 deprecated된 메소드임 
    	final StringBuilder builder = new StringBuilder();
		String errorMsg = MPlusWebErrorUtil.getErrorString(view.getContext(), errorCode);
		String lineText = view.getContext().getString(R.string.move_start_page);

		// 페이지 시작
    	builder.append("<html><title></title><body>");
    	// 에러 메시지 표시
		builder.append(MPlusWebErrorUtil.getMessageBox(errorMsg));
		// 시작화면 링크 표시
		builder.append(MPlusWebErrorUtil.getReturnURL(AddrUtil.getStartPage(), lineText));
		// 페이지 닫기
		builder.append("</body></html>");

        // 보여주기
		MPlusWebErrorUtil.loadStringData(view, builder.toString());
    }
    
    @Override 
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { 
        StringBuilder errorMsgBuilder = new StringBuilder();
        int errorCode = Integer.MAX_VALUE;

        if(error != null) {
            errorCode = error.getPrimaryError();
            errorMsgBuilder.append("code : ").append(errorCode).append("\n");
            errorMsgBuilder.append("url : ").append(error.getUrl()).append("\n");
            errorMsgBuilder.append("certifiacate : ").append(error.getCertificate());
        }

        MPlusLogUtil.ERROR(this.getClass(), "onReceivedSslError : " + errorMsgBuilder);


        final StringBuilder builder = new StringBuilder();

		// 에러 메시지 구하고
		String errorMsg = MPlusResourceUtil.getStringByName(this.activity, "mf_error_webviewclient_ssl");
		builder.append("<html><title></title><body>");
		// 에러 메시지 표시
		builder.append(MPlusWebErrorUtil.getMessageBox(errorMsg));
		// 디버깅을 위한 에러코드
		builder.append(" (code : ").append(errorCode).append(")");
		// 태그닫기
		builder.append("</p></body></html>");

        // 보여주기
		MPlusWebErrorUtil.loadStringData(view, builder.toString());
    }
}
