package com.tcl.factory.view;

import java.util.ArrayList;
import java.util.List;
//import java.util.Arrays;
import java.io.IOException;
import java.io.FileInputStream;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;
//import android.content.pm.ApplicationInfo;  
import android.content.pm.PackageManager;  
import java.util.Collections;  
//import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.ContentResolver;
import android.net.Uri;
import android.database.Cursor;

import com.tcl.factory.utils.AppInfo;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.tcl.factory.thirdparty.ThirdParty;

public class LauncherHelper {
	private Context mContext;
	private String TAG = LauncherHelper.class.getName();
	
	private String CurPowerOnAppName;
	private int curPowerOnAppIndex = 0;

	private List<String> hidePackName=new ArrayList<String>();
	private List<String> hideActivityName=new ArrayList<String>();
	private List<AppInfo> appInfoList = new ArrayList<AppInfo>();
	
	public LauncherHelper(Context context){
		mContext = context;
		
		presetAppInfo("Null");
		presetAppInfo("Launcher");
		presetAppInfo("TV");
		getAppInfosByOrder();
		CurPowerOnAppName =ThirdParty.mFactoryAdapter.getHotelLauncherAppName();
		if(CurPowerOnAppName ==null)
			CurPowerOnAppName = "null";
		Log.v(TAG, "CurPowerOnAppName = "+ CurPowerOnAppName);
		CurLauncherAppIndex();
	}

	public  List<AppInfo> getAppList(){
		Log.v(TAG, "getAppNameList");
		return appInfoList;
	}

	private void presetAppInfo(String app_name)
	{
		AppInfo appInfo = new AppInfo();
		appInfo.setmActivity(app_name);
		appInfo.setmPkg(app_name);
		appInfo.setmAppName(app_name);
		appInfoList.add(appInfo);
	}

	private void CurLauncherAppIndex(){
		for(int i = 0;i < appInfoList.size(); i ++){
			if(CurPowerOnAppName.equals(appInfoList.get(i).getmPkg()))
			{
				curPowerOnAppIndex = i;
				return;
			}			
		}			
	}

	public int getCurLauncherAppIndex(){
		Log.v(TAG, "getCurLauncherAppIndex curPowerOnAppIndex = "+curPowerOnAppIndex);
		return curPowerOnAppIndex;
	}

	public boolean setLauncherApp(int index){
		if(index ==curPowerOnAppIndex)
			return true;

		boolean ret1 = ThirdParty.setHotelLauncherAppName(appInfoList.get(index).getmPkg());
		boolean ret2 = ThirdParty.setHotelLauncherActivityName(appInfoList.get(index).getmActivity());
		if(ret1&&ret2)
		{
			curPowerOnAppIndex = index;
			return true;
		}
		else
			return false;
	}

	private void getAppInfosByOrder() {
		getHidePackageAndActivityName();
		Intent it = new Intent(Intent.ACTION_MAIN);
		it.addCategory(Intent.CATEGORY_LAUNCHER);
		PackageManager pm = mContext.getPackageManager();
		List<ResolveInfo> ra = pm.queryIntentActivities(it, 0);

		for (int i = 0; i < ra.size(); i++) {
			AppInfo appInfo = new AppInfo();

			ResolveInfo ri = ra.get(i);
			boolean isHidden = false;
			for (int j = 0; j < hideActivityName.size(); j++) {
				if (ri.activityInfo.name.equalsIgnoreCase(hideActivityName.get(j))) {
					Log.d(TAG, "not add hideActivityName.get("+j+")="+ri.activityInfo.name);
					isHidden = true;
					break;
				}
			}

			for (int k = 0; k < hidePackName.size(); k++) {
				if (ri.activityInfo.packageName
						.equalsIgnoreCase(hidePackName.get(k))) {
					Log.d(TAG, "not add hidePackName.get("+k+")="+ri.activityInfo.packageName);
					isHidden = true;
					break;
				}
			}

			if (isHidden) {
				continue;
			} else {
				appInfo.setmActivity(ra.get(i).activityInfo.name);
				appInfo.setmPkg(ra.get(i).activityInfo.packageName);
				appInfo.setmAppName(ra.get(i).loadLabel(pm).toString());
				Log.d(TAG, "apk name  = "+appInfo.getmAppName());
				appInfoList.add(appInfo);
			}
		}		
		Log.v(TAG, "get app size:" + appInfoList.size());
	}

	private void getHidePackageAndActivityName() {
		String launcherBlackList = "";
		String etcBlackList = "";
		JSONObject jsonObject = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		Uri uri = Uri.parse("content://com.tcl.cyberui.contentprovider/blacklist");

		hidePackName.add("com.tcl.settings");
		hideActivityName.add("com.tcl.settings.MainActivity");
		try {
			Cursor c = contentResolver.query(uri, null, null, null, null);
			if (c == null) {
				Log.i(TAG, "hidePackages cursor is null!!");
				String LauncherFileName = "/data/data/com.tcl.cyberui/json/black_list.json";
				String etcFileName = "/etc/black_list.json";
				etcBlackList = readJsonFile(etcFileName);
				if(etcBlackList.equals("")){
					launcherBlackList = readJsonFile(LauncherFileName);
				}
			    if (!etcBlackList.equals("")) {
					Log.i(TAG, "get black list from etc!");
					jsonObject = new JSONObject(etcBlackList);
					hidePackName = readBlackListPackName(jsonObject);
					hideActivityName = readBlackListActivityName(jsonObject);
				} else if (!launcherBlackList.equals("")) {
					Log.i(TAG, "get black list from Launcher app!");
					jsonObject = new JSONObject(launcherBlackList);
					hidePackName = readBlackListPackName(jsonObject);
					hideActivityName = readBlackListActivityName(jsonObject);
				} else {
					/*
					Log.i(TAG, "get black list from hotkey app!");
					hidePackName = Arrays.asList(HIDDEN_PACKAGE_NAME);
					hideActivityName = Arrays.asList(HIDDEN_ACTIVITY);
					*/
				}
				Log.d(TAG, "hide hidePackName="+hidePackName.toString()+" hideActivityName="+hideActivityName.toString());
			} else {
				Log.i(TAG, "hidePackages cursor is not null!!");
				try {
					if (c.moveToFirst()) {
						do {
							String package_name = c.getString(c
									.getColumnIndexOrThrow("packageName"));
							String activity_Name = c.getString(c
									.getColumnIndexOrThrow("activityName"));
							Log.d(TAG, "hide package_name="+package_name+" activity_Name="+activity_Name);
							hidePackName.add(package_name);
							hideActivityName.add(activity_Name);
						} while (c.moveToNext());

					}
				} catch (Exception e) {
					Log.i(TAG, "Exception:" + e.toString());
				} finally {
					if (c != null) {
						c.close();
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<String> readBlackListPackName(JSONObject jsonObject) throws JSONException {
		List<String> blackListPackName=new ArrayList<String>();
		JSONArray jsonArray = jsonObject.getJSONArray("black_list");
		for (int i = 0; i < jsonArray.length(); i++) {
		    JSONObject object = jsonArray.getJSONObject(i);
		    Log.i(TAG, "----------------");
		    Log.i(TAG, "package_name=" + object.getString("package_name"));
		    blackListPackName.add(object.getString("package_name"));
		}
		return blackListPackName;
	}

	private List<String> readBlackListActivityName(JSONObject jsonObject) throws JSONException {
		List<String> blackListActivityName=new ArrayList<String>();
		JSONArray jsonArray = jsonObject.getJSONArray("black_list");
		for (int i = 0; i < jsonArray.length(); i++) {
		    JSONObject object = jsonArray.getJSONObject(i);
		    Log.i(TAG, "----------------");
		    Log.i(TAG, "package_name=" + object.getString("package_name"));
		    Log.i(TAG, "activity_name=" + object.getString("activity_name"));
		    blackListActivityName.add(object.getString("activity_name"));
		}
		return blackListActivityName;
	}

	private String readJsonFile(String fileName) throws IOException {
        String res = "";
        try {            
            FileInputStream fin = new FileInputStream(fileName);
            int length = fin.available();
            try{
	            byte[] buffer = new byte[length];
	            fin.read(buffer);	            
	            res = EncodingUtils.getString(buffer, "UTF-8");
            	} catch (Exception e) {
			e.printStackTrace();
	        } finally {
			if (fin != null) {
				fin.close();
			}
		}          
        } catch (Exception e) {
            e.printStackTrace();
        } 
        Log.i(TAG, "fileName:"+fileName);
        Log.i(TAG, "res:"+res);
        return res;
    }
}
