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

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.dbs.mplus.fatima.consent.sign.SignWrapper;
import com.dbs.mplus.fatima.framework.MPlusFrameworkConstants;
import com.dbs.mplus.fatima.framework.util.MPlusLogUtil;
import com.dbs.mplus.fatima.framework.util.MPlusStringUtil;
import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.receiver.PushMessageAlertReceiver;
import com.dbs.mplus.fatima.util.AddrUtil;
import com.dbs.mplus.fatima.util.IntentUtil;

import java.util.Iterator;
/**
 * 앞단에 LoadingActivity가 있지만, 실제 Main activity 
 * @author aple
 *
 */
public class MPlusWebActivity extends Activity {
    private MPlusWebViewWrapper webViewWrapper;
    private PushMessageAlertReceiver pushReceiver;   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); 
        this.setContentView(R.layout.activity_mcare_web);
        
        MPlusLogUtil.DEBUG(this.getClass(), "WebView 시작 : " + IntentUtil.getIntentString(this.getIntent()));

        // Push를 받을 수 있는 리시버 생성 
        this.pushReceiver = new PushMessageAlertReceiver(); 
        
        // 주소 로딩하기
        this.loadingUrl(this.getIntent());    
    }

//    @Override
//    protected void onNewIntent (Intent intent) {
//        super.onNewIntent(intent);
//
//        MPlusLogUtil.DEBUG(MPlusWebActivity.class, IntentUtil.getIntentString(intent));
//    }
//
    @Override 
    protected void onResume() { 
    	super.onResume(); 

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

    	final LocalBroadcastManager m = LocalBroadcastManager.getInstance(this);

		if(Build.VERSION.SDK_INT < 21) {
			CookieSyncManager.getInstance().sync();
		}
    	
    	if(m != null) { 
    		IntentFilter filter = null;
    		
    		// push 관련 메시지를 받을 수 있도록 조치하고 
    		filter = new IntentFilter(MPlusFrameworkConstants.ACTION_PUSH);
    		m.registerReceiver(this.pushReceiver, filter);
    	}
    }
    
    @Override 
    protected void onPause() { 
    	MPlusLogUtil.DEBUG(this.getClass(), "onPause");
    	
    	
    	final LocalBroadcastManager m = LocalBroadcastManager.getInstance(this); 
    	if(m != null) { 
    		m.unregisterReceiver(this.pushReceiver);
    	}

		if(Build.VERSION.SDK_INT < 21) {
			CookieSyncManager.getInstance().stopSync();
		}
    	
    	super.onPause(); 
    }
    
    @Override 
    protected void onSaveInstanceState (Bundle outState) {
    	MPlusLogUtil.DEBUG(this.getClass(), "onSaveInstanceState : " + outState);
    	outState.putString(MPlusFrameworkConstants.MSG_VALUE_KEY.BROWSING_URL.toString(), this.webViewWrapper.getPageUrl());
    	
    	if(outState != null) {
    		final Iterator<String> keyIter = outState.keySet().iterator(); 
    		String key = null; 
    		final StringBuilder builder = new StringBuilder(); 
    		
    		while(keyIter.hasNext()) {
    			key = keyIter.next(); 
    			builder.append(key).append(" : ").append(outState.get(key)).append("\n"); 
    		}
    		
    		MPlusLogUtil.DEBUG(this.getClass(), builder.toString());
    	}
    }
    
    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
    	super.onConfigurationChanged(newConfig);
    }
    
	@Override
    protected void onDestroy() { 
    	super.onDestroy();   
    	MPlusLogUtil.DEBUG(this.getClass(), "onDestroy");

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

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	switch(keyCode) { 
    	case KeyEvent.KEYCODE_HOME : // system에서 override되서 폰의 홈 화면으로 이동됨 
    		return true; 
    		
    	case KeyEvent.KEYCODE_BACK : // 화면마다 back이 달라서 무시함 
    		this.webViewWrapper.loadUrl("javascript:triggerBackBtn();");
    		return true; 
    		
    	case KeyEvent.KEYCODE_MENU : 
    		this.webViewWrapper.loadUrl("javascript:triggerSidebarBtn()");
    		return true; 
    	}
    	
    	return super.onKeyDown(keyCode, event); 
    }
    
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 
    	final MPlusFrameworkConstants.ACTIVITY_REQUEST_CODE code = MPlusFrameworkConstants.ACTIVITY_REQUEST_CODE.search(requestCode);

        StringBuilder builder = new StringBuilder();
        builder.append("onActivityResult : ");
        builder.append("requestCode=").append(requestCode).append(", ");
        builder.append("code=").append(code).append(", ");
        builder.append("resultCode=").append(resultCode).append(", ");
        builder.append("intent=").append(IntentUtil.getIntentString(intent));
        MPlusLogUtil.DEBUG(this.getClass(), builder.toString());

        if(code == null) {
            MPlusLogUtil.ERROR(this.getClass(), "code가 없어서 무시");
            return;
        }

        switch(code) {
			case GOOGLE_API_AVAILABILITY_USER_RESOLVABLE_ERROR_DIALOG : // 구글플레이 서비스를 사용할 수 있도록 사용자가 보완하고 온 경우
				// 경대병원에서는 아무것도 안했는데..
				MPlusLogUtil.DEBUG(this.getClass(), "GOOGLE_API_AVAILABILITY_USER_RESOLVABLE_ERROR_DIALOG");
				break;

			case AFTER_EXTRA_POPUP: // ExtraPopup이 닫히는 경우
				MPlusLogUtil.DEBUG(this.getClass(), "AFTER_EXRA_POPUP");
                String callBack = intent.getStringExtra(MPlusFrameworkConstants.MSG_VALUE_KEY.CALLBACK_FN.toString());
                if(callBack != null) {
                    this.webViewWrapper.loadUrl(MPlusStringUtil.getCallbackFnString(callBack));
                }
				break;
    	}
    }
   

    /**
     * 해당 주소 로딩하기 
     * @param intent 로딩할 정보
     */
    private void loadingUrl(Intent intent) { 
        // 초기화에 사용될 URL 
        String loading = AddrUtil.getStartPage(); 
       
    	// 초기에 로딩되었는지, 브라우징 명령에 의해 로딩되었는지 확인해서 이동 필요 
    	// 브라우징 명령에 의해 로딩된 것이라면 해당 주소로 이동 
        if(intent != null) {
        	// 꺼내서 
        	final Bundle b = intent.getExtras(); 
        	if(b != null) { 
        		// Action 확인 
        		final String action = b.getString(MPlusFrameworkConstants.ACTION_KEY);
        		
        		// 명시적인 주소 브라우징 or 백업해둔 주소를 복원해서 보는 화면인가 
        		if(MPlusFrameworkConstants.ACTION_BROWSING.equals(action)) {
                	final String browsingURL = b.getString(MPlusFrameworkConstants.MSG_VALUE_KEY.BROWSING_URL.toString());
                	if(!MPlusStringUtil.isEmpty(browsingURL)) {
                		loading = browsingURL; 
                	}
        		}
        	}
        }
        
        // 없을때만 만들면 되는 것들 
        if(this.webViewWrapper == null) { 
            // 만들고
            this.webViewWrapper = new MPlusWebViewWrapper(
                    this,
                    (ProgressBar) this.findViewById(R.id.webViewPB),
                    (WebView) this.findViewById(R.id.webView));
            
            // 초기화한 다음에
            this.webViewWrapper.init();
        }

        // 지정된 url이나 script등등...
        // 브라우저로 해야할 일 하기  
        this.webViewWrapper.loadUrl(loading);

    }

	@Override
	public void finish() {
		// 인증서 모두 정리
		SignWrapper.getInstance().deleteAll();
		super.finish();
	}
}
