package BWP.MobileSale;

import org.forks.jsonrpc.JsonRpcException;
import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.platform.AndroidPlatform;
import org.forks.jsonrpc.platform.Platform;



import BWP.MobileSale.Config.LastLoginInfo;
import BWP.MobileSale.Util.ConfigUtil;
import BWP.MobileSale.Util.StringUtil;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.StrictMode;
import android.util.Log;

@SuppressLint("NewApi")
public class SaleApplication extends Application {
	
	
	static LastLoginInfo mLoginInfo; 
	@Override
	public void onCreate() {
	   	String strVer=android.os.Build.VERSION.RELEASE;
    	strVer=strVer.substring(0,3).trim();
    	float fv=Float.valueOf(strVer);
    	if(fv>2.3)
    	{
    		
    		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
    		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
       	}
		
		super.onCreate();
		
		Platform.init(new AndroidPlatform(this));
		RpcFacade.init("AndroidSale");
		mLoginInfo = new LastLoginInfo(this);
		ConfigUtil.Fill(mLoginInfo);		
		reLogin();
	}
	

	private void reLogin() {
		
		if (RpcFacade.isLogedIn()) {
			return;
		}

		if (StringUtil.IsNullOrEmpty(mLoginInfo.Username)) {
			return;
		}

		long currentTimeMillis = System.currentTimeMillis();
		if (currentTimeMillis - mLoginInfo.CurrentTimeMillis > 30 * 60 * 1000) {
			return;
		}

		try {
			RpcFacade.login(mLoginInfo.Username, mLoginInfo.Password);
		} catch (JsonRpcException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void UpdateLastActiveTime() {
		if(StringUtil.IsNullOrEmpty(mLoginInfo.Username)){
			Log.e("SaleApplication", "还没有登录，不能调用UpdateLastActiveTime()方法");
			return;
		}
		mLoginInfo.CurrentTimeMillis = System.currentTimeMillis();
		ConfigUtil.Save(mLoginInfo);
	}
	
	public static void ClearLogin(){
		mLoginInfo.Username = "";
		ConfigUtil.Save(mLoginInfo);
	}
	
	public static void SaveLogin(String username,String password){
		mLoginInfo.Username = username;
		mLoginInfo.Password = password;
		mLoginInfo.CurrentTimeMillis = System.currentTimeMillis();
		ConfigUtil.Save(mLoginInfo);
	}

}
