package com.usai.apex;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.usai.util.AES;
import com.usai.util.RAUtil;
import com.usai.util.dbUtil;

import java.io.File;

public class ApexTrackingApplication extends Application
{

	static final String						TAG				= "ApexTrackingApplication";
	private static ApexTrackingApplication	instance;
//	private static String					m_sessionid		= "";
	private static String					m_user			= "";
	private static String					m_password		= "";
	public static int						ncount			= 1;

	public static boolean					m_bauthorized	= false;
	private boolean 							personMode 		= false;

	public boolean homeactive=false;
	public boolean historyactive=false;
	public boolean recentactive=false;
	private static long LastAlermTime = -120000;
	
	public static void UpdateLastCheckMessageTime()
	{
		LastAlermTime = SystemClock.elapsedRealtime();
	}
	public static long getLastCheckMessageTime()
	{
		return LastAlermTime;
	}

	public void setPersonMode(boolean personMode) {
		this.personMode = personMode;
	}

	public boolean getPersonMode() {
		return this.personMode;
	}

	public static ApexTrackingApplication getInstance() {
		return instance;
	}
	@Override
	public void onCreate()
	{

		// TODO Auto-generated method stub
		Log.d(TAG, "onCreate");
		super.onCreate();


		registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
			@Override
			public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
				Resources res = ApexTrackingApplication.getInstance().getResources();
				Configuration config = new Configuration();
				config.setToDefaults();
				res.updateConfiguration(config, res.getDisplayMetrics());
			}

			@Override
			public void onActivityStarted(Activity activity) {

//				// 加载系统默认设置，字体不随用户设置变化
//				Resources res = ApexTrackingApplication.getInstance().getResources();
//				Configuration config = new Configuration();
//				config.setToDefaults();
//				res.updateConfiguration(config, res.getDisplayMetrics());
			}

			// ...
			@Override
			public void onActivityResumed(Activity activity) {
//				if (isBackground) {
//					isBackground = false;
//					notifyForeground();
//				}
			}

			@Override
			public void onActivityPaused(Activity activity) {

			}

			@Override
			public void onActivityStopped(Activity activity) {

			}

			@Override
			public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

			}

			@Override
			public void onActivityDestroyed(Activity activity) {

			}
			// ...
		});

		// 加载系统默认设置，字体不随用户设置变化
		Resources res = super.getResources();
		Configuration config = new Configuration();
		config.setToDefaults();
		res.updateConfiguration(config, res.getDisplayMetrics());

		instance = this;

		SharedPreferences pref = ApexTrackingApplication.get_instance()
				.getSharedPreferences("Apex", 0);
		boolean autologin = pref.getBoolean("autologin", false);
		if (autologin == true)
		{

			String u = pref.getString("user", "");
			String p = pref.getString("password", "");
//			String s = pref.getString("sessionid", "");

			try
			{
				if (!TextUtils.isEmpty(u))
					m_user = AES.decrypt("apexu", u);
				if (!TextUtils.isEmpty(p))
					m_password = AES.decrypt("apexp", p);
//				if (!TextUtils.isEmpty(s))
//					m_sessionid = AES.decrypt("apexp", s);
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		dbUtil.cleanhistory();

		// Intent serviceintent = new Intent();
		// serviceintent.setClass(this, ApexPushService.class);
		//
		//
		// startService(serviceintent);

		createAppStorageDir();
	}

	public void createAppStorageDir() {
		String documentDir = getDocumentDir();
		File docDir = new File(documentDir);
		docDir.mkdirs();

	}

	public String getDocumentDir() {
//		return RAUtil.SDCardRoot() + RAUtil.getApplicationName(getApplicationContext()) + File.separator +"Document";
		return RAUtil.SDCardRoot() + RAUtil.getApplicationName(getApplicationContext());
	}

	// @Override
	// protected void finalize() throws Throwable
	// {
	// NotificationManager nManager = (NotificationManager)
	// instance.getSystemService(
	// Context.NOTIFICATION_SERVICE);
	// nManager.cancel(R.layout.activity_apex);
	// super.finalize();
	// }

	public static ApexTrackingApplication get_instance()
	{
		return instance;
	}

	public static void startalarm(String caller)
	{
		// 新版暂时停用通知
		if(true)
			return;
		SharedPreferences pref = get_instance()
				.getSharedPreferences("Apex", 0);
		boolean autologin = pref.getBoolean("autologin", false);
		if (autologin == false)
			return;
		// 启动完成
		Intent iAlarm = new Intent(get_instance(), Alarmreceiver.class);
		iAlarm.putExtra("caller", caller);
		iAlarm.setAction("com.usai.apex.push");
		PendingIntent sender = PendingIntent.getBroadcast(get_instance(), 0,
				iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);

		long firstime = SystemClock.elapsedRealtime();
//		UpdateLastAlermTime();
		AlarmManager am = (AlarmManager) get_instance().getSystemService(
				Context.ALARM_SERVICE);

		// 5分钟一个周期，不停的发送广播
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,
				300 * 1000, sender);
	}

	public static void cancelalarm()
	{

		// 启动完成
		Intent iAlarm = new Intent(get_instance(), Alarmreceiver.class);
		iAlarm.setAction("com.usai.apex.push");
		PendingIntent sender = PendingIntent.getBroadcast(get_instance(), 0,
				iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager am = (AlarmManager) get_instance().getSystemService(
				Context.ALARM_SERVICE);

		am.cancel(sender);
	}

	public static void logout()
	{
		ncount = 1;
		cancelalarm();
//		m_sessionid = "";
		m_user = "";
		m_password = "";
		m_bauthorized = false;
		get_instance().setPersonMode(false);
		SharedPreferences pref = ApexTrackingApplication.get_instance()
				.getSharedPreferences("Apex", 0);
		SharedPreferences.Editor editor = pref.edit();

		editor.putBoolean("autologin", false);
		editor.commit();

	}

	public static void SetAuthorizeStatus(boolean bauthorized)
	{
		m_bauthorized = bauthorized;
	}
	public static void login(String sid, String user, String pass)
	{
//		m_sessionid = sid;
		m_user = user;
		m_password = pass;
		m_bauthorized = true;
		
		SharedPreferences pref = ApexTrackingApplication.get_instance()
				.getSharedPreferences("Apex", 0);
		SharedPreferences.Editor editor = pref.edit();
		try
		{

			editor.putString("user", AES.encrypt("apexu", m_user));
			editor.putString("password", AES.encrypt("apexp", m_password));
			editor.putBoolean("autologin", true);
//			editor.putString("sessionid", AES.encrypt("apexp", m_sessionid));

		}
		catch (Exception e)
		{
			editor.putString("user", null);
			editor.putString("password", null);
//			editor.putString("m_sessionid", null);
			editor.putBoolean("autologin", false);
			m_bauthorized=false;
			e.printStackTrace();
		}
		editor.commit();

		startalarm("app Login");
	}

	// public static void put_sessionid(String id)
	// {
	//
	// Log.e(TAG, "put_sessionid");
	// m_sessionid = id;
	// }

	// public static void put_authorization(boolean bauth)
	// {
	//
	// m_bauthorized = bauth;
	// }

	public static boolean get_authorization()
	{

		return m_bauthorized;
	}

	// public static void put_user(String user)
	// {
	//
	// m_user = user;
	// }
	//
	// public static void put_password(String pass)
	// {
	//
	// m_password = pass;
	// }

//	public static String get_sessionid()
//	{
//		Log.d(TAG, "get_sessionid");
//		return m_sessionid;
//	}

	public static String get_user()
	{
		Log.d(TAG, "get_user");
		return m_user.toLowerCase();
	}

	public static String get_pass()
	{
		Log.d(TAG, "get_pass");
		return m_password;
	}
}
