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

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;

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

import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.List;

/**
 * 서비스 관련 유틸 
 * @author aple
 *
 */
public class MPlusServiceUtil {
	/**
	 * 알림바 내용 지우기 
	 * 코드는 짧지만 한군데서 다 추적하기 위함 
	 * @param context
	 */
	public static void cancelAllNotification(Context context) { 
    	final NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    	notiManager.cancelAll(); 		
	}
//	
//	/**
//	 * Activity 실행중인지 확인 
//	 * @param context
//	 * @param activityClass
//	 * @return
//	 */
//	public static boolean isActivityRunning(Context context, Class<?> activityClass) {
//		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//		List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
//		
//		for (ActivityManager.RunningTaskInfo task : tasks) {
//			MPlusLogUtil.DEBUG(MPlusServiceUtil.class, task.baseActivity.getClassName());
//			if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName())) {
//			    return true;
//			} 
//		}
//		
//		return false;
//	}	

	/**
	 * 수신 정보를 파싱해서 Bundle형태로 묶기 
	 * @param context
	 * @param data
	 * @return
	 */
	public static Bundle parsePushBundle(Context context, Bundle data) {
		final Bundle bundle = new Bundle();
		String message = null;

		// URLEncoding되어 오는 경우는 디코딩 하고, 디코딩 안되면 그냥 쓰고 
		try {
			message = URLDecoder.decode(data.getString("MSG"), "UTF-8");
		}
		catch(final Exception ex) {
			MPlusLogUtil.DEBUG(MPlusServiceUtil.class, "디코딩 필요없는 것으로 인식  " + data);
			message = data.getString("MSG");
		}

		// JSON분석 
		try {
			// JSON분석 
			final JSONObject obj = new JSONObject(message);

			// 번들에 심기 
			bundle.putString(MPlusFrameworkConstants.KEY_NOTI_PUSH_ID, data.getString(MPlusFrameworkConstants.KEY_NOTI_PUSH_ID));
			bundle.putString(MPlusFrameworkConstants.KEY_NOTI_PUSH_PID, obj.getString(MPlusFrameworkConstants.KEY_NOTI_PUSH_PID));
			bundle.putString(MPlusFrameworkConstants.KEY_NOTI_PUSH_TITLE, obj.getString(MPlusFrameworkConstants.KEY_NOTI_PUSH_TITLE));
			bundle.putString(MPlusFrameworkConstants.KEY_NOTI_PUSH_REGDT, obj.getString(MPlusFrameworkConstants.KEY_NOTI_PUSH_REGDT));
		}
		catch(final Exception ex) {
			MPlusLogUtil.ERROR(MPlusServiceUtil.class, "push 분석 에러 : " + data.getString("MSG"), ex);
			// 메시지가 왔다는 사실은 알 수 있도록 
			bundle.putString(MPlusFrameworkConstants.KEY_NOTI_PUSH_ID, data.getString(MPlusFrameworkConstants.KEY_NOTI_PUSH_ID));
			bundle.putString(MPlusFrameworkConstants.KEY_NOTI_PUSH_TITLE, MPlusResourceUtil.getStringByName(context, "mf_message_received"));
		}

		//MPlusLogUtil.DEBUG(MPlusServiceUtil.class, "parsePushBundle : " + message);

		return bundle;
	}
	
	/**
	 * 서비스가 구동중인지 확인 
	 * @param appCtx
	 * @param serviceClassName
	 * @return
	 */
	public static boolean isServiceRunning(Context appCtx, String serviceClassName) { 
		final ActivityManager activityManager = (ActivityManager) appCtx.getSystemService(Context.ACTIVITY_SERVICE); 
		final List<RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE); 
		
		for(final RunningServiceInfo info : serviceList) { 
			if(info.service.getClassName().equals(serviceClassName)) {
				return true; 
			}
		}

		return false; 
	}
	
	/**
	 * 앱이 백그라운드로 실행되고 있는지 확인
	 * @param context
	 * @return
	 */
	public static boolean isApplicationBackground(Context context) {
		final ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		final List<RunningAppProcessInfo> list = am.getRunningAppProcesses();
		
		// 실행되고 있는 앱을 하나씩 검사하고 
		for(final RunningAppProcessInfo rap : list) {
			// 내 앱이면 
			if(rap.processName.equals(context.getPackageName())) {
				return (rap.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND); 
			}
		}
		
		// 실행안하고 있으면 background인걸로 
		return true;
	}

	/**
	 * 해당 패키지명이 설치되어 있는지 여부 확인
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean isAppInstalled(Context context, String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);

            return true;
        }
        catch(NameNotFoundException ex) {
            MPlusLogUtil.ERROR(MPlusServiceUtil.class, ex.toString());
            return false;
        }

	}
	
	/**
	 * 디버깅용
	 * @param context
	 * @return
	 */
	public static String getActivityStackList(Context context) {
		final StringBuilder builder = new StringBuilder("\n");
		final ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		final List<RunningTaskInfo> taskIter = am.getRunningTasks(10);

		for(final RunningTaskInfo info : taskIter) {
			builder.append("- task id : ").append(info.id).append("\n");
			builder.append("  * top : ").append(info.topActivity.getShortClassName()).append("\n");
			builder.append("  * base : ").append(info.baseActivity.getShortClassName()).append("\n");
			builder.append("  * activities : ").append(info.numRunning).append("/").append(info.numActivities).append("\n");
			builder.append("  * desc : ").append(info.description).append("\n");
		}

		return builder.toString();
	}
}
