package com.dbs.mplus.fatima.framework.util;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;

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

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

/**
 * 천지사방에 Intent가 널려있는것을 방지하기 위한 유틸 
 * Intent는 여기에서만 만들어 사용한다. 
 * 
 * @author aple
 *
 */
public class MPlusIntentUtil {
	private static final int INTENT_FLAG = Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP;
	
	/**
	 * 앱 다시 런칭하기 
	 * @param context
	 * @return
	 */
	public static Intent getLaunchIntent(Context context) { 
		return context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); 
	}
	
	/**
	 * 새로운 url로 브라우징 
	 * @param context 
	 * @param clazz 브라우징을 처리할 클래스 
	 * @param url
	 * @return
	 */
	public static Intent getBrowsingIntent(Context context, Class<?> clazz, String url) { 
        final Intent intent = new Intent(context,clazz);
        intent.putExtra(MPlusFrameworkConstants.ACTION_KEY, MPlusFrameworkConstants.ACTION_BROWSING);
        intent.putExtra(MPlusFrameworkConstants.MSG_VALUE_KEY.BROWSING_URL.toString(), url);

        return intent; 
	}
	
	
	
	/**
	 * 시작주소로 브라우징 
	 * @param appContext
	 * @return
	 */
	public static Intent getDefaultBrowsingIntent(Context appContext, Class<?> activityClazz, String basePage) { 
        final Intent intent = new Intent(appContext, activityClazz);
        final MPlusPreferenceUtil p = MPlusPreferenceUtil.getInstance(appContext);
        final String url = p.getStartPage(basePage); 

        intent.setFlags(MPlusIntentUtil.INTENT_FLAG | Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.setFlags(MPlusIntentUtil.INTENT_FLAG); 이러면 로딩화면이 지나고 앱이 죽을 것이다.
        intent.putExtra(MPlusFrameworkConstants.ACTION_KEY, MPlusFrameworkConstants.ACTION_BROWSING);
        intent.putExtra(MPlusFrameworkConstants.MSG_VALUE_KEY.BROWSING_URL.toString(), url);
        
        
        //MPlusLogUtil.DEBUG(MPlusIntentUtil.class, "getDefaultBrowsingIntent. url=" + url);
        
        return intent; 
	}	
	
	/**
	 * 앱 시작 
	 * @param appContext
	 * @param action
	 * @param url
	 * @return
	 */
	public static Intent getStartApp(Context appContext, String action, String url) { 
		final Intent intent = appContext.getPackageManager().getLaunchIntentForPackage(appContext.getPackageName());
		//intent.setFlags(IntentUtil.INTENT_FLAG | Intent.FLAG_ACTIVITY_NEW_TASK); 
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setAction(action); 
		intent.putExtra(MPlusFrameworkConstants.PARAM_START_URL, url);
		
		//MPlusLogUtil.DEBUG(MPlusIntentUtil.class, "getStartApp. url=" + url);
		
		return intent; 
	}

	/**
	 * 시스템에 설치된 브라우저로 브라우징 
	 * @param url
	 * @return
	 */
	public static Intent getSystemBrowsingIntent(String url) { 
		final Intent intent = new Intent(Intent.ACTION_VIEW); 
		intent.setData(Uri.parse(url)); 
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		
		return intent; 
	}

	/**
	 * Push 수신 알림 
	 * @param bundle
	 * @return
	 */
	public static Intent getPushNotificationIntent(Bundle bundle) { 
		final Intent intent = new Intent(MPlusFrameworkConstants.ACTION_PUSH);
		// bundle의 내용 복사해넣기 
		if(bundle != null) { 
			intent.putExtras(bundle); 
		}
		
		return intent; 
	}
	
	/**
	 * setting 화면으로 이동 
	 * @return
	 */
	public static Intent getSettingIntent() {
		return new Intent(Settings.ACTION_SETTINGS);
	}
	
	/**
	 * 마켓으로 가기 
	 * @param marketUrl
	 * @return
	 */
	public static Intent getOpenMarketIntent(String marketUrl) { 
		final Intent i = new Intent(Intent.ACTION_VIEW); 
		
		try { 
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			i.setData(Uri.parse(marketUrl)); 
		}
		catch(final Exception ex) {
			MPlusLogUtil.ERROR(MPlusIntentUtil.class, "marketUrl : " + marketUrl);
		}
		
		return i; 
	}

	/**
	 * 주어진 uri 보기
	 * @param uri
	 * @return
	 */
	public static Intent getOpenUri(Uri uri) {
		final Intent i = new Intent(Intent.ACTION_VIEW, uri);

		try {
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		}
		catch(final Exception ex) {
			MPlusLogUtil.ERROR(MPlusIntentUtil.class, "uri : " + uri);
		}

		return i;
	}
	

	/**
	 * 전화걸기 
	 * @param url
	 * @return
	 */
	public static Intent getPhoneCallIntent(String url) { 
		final Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url)); 
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		
		return intent; 
	}

	/**
	 * 메일 보내기
	 * @param url
	 * @return
	 */
	public static Intent getMailSendIntent(String url) {
		Uri parsedUri = null;

		try {
			parsedUri = Uri.parse(url);
		}
		catch(Exception ex) {
			MPlusLogUtil.ERROR(MPlusIntentUtil.class, "fail to parse url : " + url);
			return null;
		}

		final Intent intent = new Intent(Intent.ACTION_SENDTO, parsedUri);
		return intent;
	}

	/**
	 * 앱 종료 시, Home activity를 불러주기 위함 
	 * @return
	 */
	public static Intent getHomeIntent() { 
		final Intent intent = new Intent(Intent.ACTION_MAIN); 
		
		intent.addCategory(Intent.CATEGORY_HOME); 
		intent.setFlags(MPlusIntentUtil.INTENT_FLAG | Intent.FLAG_ACTIVITY_NEW_TASK);
		
		return intent; 
	}
	
	/**
	 * 스케줄 추가 
	 * @param title
	 * @param location
	 * @param desc
	 * @param startDt
	 * @return
	 */
	public static Intent getCalendarEventIntent(String title, String location, String desc, Date startDt) { 
		final Intent intent = new Intent(Intent.ACTION_INSERT); 
		
		//intent.setData(CalendarContract.Events.CONTENT_URI); 
		intent.setType("vnd.android.cursor.item/event"); 
		intent.putExtra(Events.TITLE, title); 
		intent.putExtra(Events.EVENT_LOCATION, location); 
		intent.putExtra(Events.DESCRIPTION, desc); 
		// 시간 
		final GregorianCalendar c = new GregorianCalendar(); 
		c.setTime(startDt);
		// 진료 종료시간은 알 수 없으니까 시작이랑 종료 날짜를 동일하게 처리 
		intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startDt.getTime()); 
		intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, startDt.getTime()); 
		
		
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		return intent; 
	}

	/**
	 * text 형식의 data share intent 만들기
	 * @param data
	 * @return 비어있는 문자열이면 처리하지 않음
	 */
	public static Intent getTextDataShare(String data) {
		if(MPlusStringUtil.isEmpty(data)) {
			return null;
		}

		Intent sendIntent = new Intent();

		sendIntent.setAction(Intent.ACTION_SEND);
		sendIntent.putExtra(Intent.EXTRA_TEXT, data);
		sendIntent.setType("text/plain");

		return sendIntent;
	}


	/**
	 * TTS data install
	 * @return
	 */
	public static Intent getTtsInstallIntent() {
		Intent intent = new Intent();
		intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
		return intent;
	}
	/**
	 * tts data 확인
	 * @return
	 */
	public static Intent getCheckTtsData() {
		Intent intent = new Intent();
		intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);

		return intent;
	}

//	/**
//	 * tts 읽어주는 화면
//	 * @param context
//	 * @param data
//	 * @return
//	 */
//	public static Intent getSpeakingIntent(Context context, String data) {
//		Intent intent = new Intent(context, MCareSpeakingActivity.class);
//
//		intent.setAction(MPlusFrameworkConstants.ACTION_SPEAK);
//		intent.putExtra(MPlusFrameworkConstants.PARAM_SPEAK_TEXT, data);
//		intent.setFlags(MPlusIntentUtil.INTENT_FLAG | Intent.FLAG_ACTIVITY_NEW_TASK);
//
//		return intent;
//	}
//

	/**
	 * Intent를 문자열로 표현 
	 * @param intent
	 * @return
	 */
	public static String getIntentString(Intent intent)  {
		if(intent == null) { 
			return null; 
		}
		
		final StringBuilder builder = new StringBuilder(); 
		final Bundle bundle = intent.getExtras(); 
		
		builder.append("action : ").append(intent.getAction()).append("\n");
		builder.append("data : ").append(intent.getData()).append("\n");

		if(bundle != null) { 
			final Iterator<String> keyIter = bundle.keySet().iterator(); 
			String key = null; 
			
			while(keyIter.hasNext()) {
				key = keyIter.next(); 
				
				builder.append(key).append(" : ").append(bundle.get(key)).append(", "); 
			}
			
			builder.append(", packageName : ").append(intent.getPackage()); 
		}
		
		return builder.toString(); 
	}

}
