/**
 * 文件名：MiniApp.java
 * 描述：自定义Application(初始化并持有一些全局数据)
 * 包名：cn.com.kmlt.monstarBase.utils.base
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.utils.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Debug;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.mgq.base.utils.net.NetworkStatus;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.util.Locale;


/**
 * Application入口
 * 
 * @author WENJQ
 */
public class MiniApp extends Application {


	public static final String TAG = "MiniApp";

	//应用上下文
	private static Context mContext;

    //是否已登录的标记
	public static boolean isLogined = false;
	
    //网络是否"在线"的标记	
	public static boolean isOnline = false;
	
	public static String cookies = "";

	public static int curPage = 0;

	private Handler handler;

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onCreate() {
		super.onCreate();

		mContext = getApplicationContext();
		// 获得当前设备的屏幕参数
		DisplayMetrics dm = new DisplayMetrics();
		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;
		int screenHeight = dm.heightPixels;
		deviceWidth = screenWidth;
		deviceHeight = screenHeight;
		density = dm.density;

		initImageLoader(mContext);
	}

	/**
	 * 当前设备宽度
	 */
	private static int deviceWidth;

	/**
	 * 当前设备高度
	 */
	private static int deviceHeight;

	/**
	 * 当前设备分辨率
	 */
	private static float density;

	public static Context getContext() {
		return mContext;
	}

	public static int getDeviceWidth() {
		return deviceWidth;
	}

	public static int getDeviceHeight() {
		return deviceHeight;
	}

	public static float getDensity() {
		return density;
	}

	public static int dip2px(float dipValue) {
		final float scale = density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(float pxValue) {
		final float scale = density;
		return (int) (pxValue / scale + 0.5f);
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		//    Logger.v(TAG, "App onLowMemory()");
	}

	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		super.onTerminate();
		//    Logger.v(TAG, "App onTerminate()");
	}
	public static void MemoryInfo(){
	    Runtime rt = Runtime.getRuntime();
	    long vmAlloc =  rt.totalMemory() - rt.freeMemory();
	    long nativeAlloc = Debug.getNativeHeapAllocatedSize();
/*	    Logger.d("wy", "------------------------------");
	    Logger.d("wy", "MAX MEMORY:"+Runtime.getRuntime().maxMemory()/1024/1024+"MB");
	    Logger.d("wy", "vmHeap:"+formatMemoeryText(rt.totalMemory()));
	    Logger.d("wy", "vm分配："+formatMemoeryText(vmAlloc));
	    Logger.d("wy", "本地分配："+formatMemoeryText(nativeAlloc));
	    Logger.d("wy", "总分配："+formatMemoeryText(nativeAlloc+vmAlloc));
	    Logger.d("wy", "本地heap:"+formatMemoeryText(Debug.getNativeHeapSize()));*/
	}
	private static String formatMemoeryText(long memory) {
		float memoryInMB = memory * 1f / 1024 / 1024;
		return String.format(Locale.CHINA, "%.1f MB", memoryInMB);
	}
	
	public  void SystemGc(){
	    System.gc();
	}

	public static void saveLoginName(Context context, String name)
	{
		if (context == null)
		{
			return;
		}
		SharedPreferences sharedPreferences = context.getSharedPreferences("kmlt", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("username_phone", name);
		editor.apply();
	}

	public static String getLoginName(Context context)
	{
		if (context == null)
		{
			return null;
		}
		SharedPreferences sharedPreferences = context.getSharedPreferences("kmlt", Activity.MODE_PRIVATE);
		return sharedPreferences.getString("username_phone", "");
	}

    public static void saveLoginUserInfo(Context context, String jsonStr)
    {
        if (context == null)
        {
            return;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences("kmlt", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("userinfo_json", jsonStr);
		editor.apply();
	}

    public static String getLoginUserInfo(Context context)
    {
        if (context == null)
        {
            return null;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences("kmlt", Activity.MODE_PRIVATE);
        return sharedPreferences.getString("userinfo_json", "");
    }

    public static void syncCookie(Context context, String url) {
        try {
            Log.d("Nat: ", url);

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if (oldCookie != null) {
                Log.d("Nat: ", oldCookie);
            }

            String[] pair = cookies.split(";");
            for (int i = 0; i < pair.length; ++i) {
                cookieManager.setCookie(url, pair[i]);
            }

            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                Log.d("Nat: ", newCookie);
            }
        } catch (Exception e) {
            Log.e("Nat: ", e.toString());
        }
    }

    // 移除用户cookie信息
    public static void clearCookie(Context context)
    {
        CookieSyncManager.createInstance(context);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeSessionCookie();// 移除
        cookieManager.removeAllCookie();
    }

    public static String getCookie(Context context, String url)
    {
        CookieSyncManager.createInstance(context);

        CookieManager cookieManager = CookieManager.getInstance();
        return cookieManager.getCookie(url);
    }

	public static boolean isNetworkConnected(Context context){
		return NetworkStatus.isNetworkConnected(context);
	}

	public static void permissionError(int errorCode)
	{
        //if (errorCode != null && errorCode.equals("对不起, 您还未登录"))
		if (errorCode == 403 && isLogined) {
			isLogined = false;

            clearCookie(getContext());
            saveLoginUserInfo(getContext(), "");

/*            endPaiduPush();

            MainActivity.showPermissAlert();*/
        }
    }

	public static DisplayImageOptions circDisplayImageOptions = new DisplayImageOptions.Builder().considerExifParams(true)
			.resetViewBeforeLoading(true).cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
			.delayBeforeLoading(100)
			.displayer(new RoundedBitmapDisplayer(180))
			.build();

	public static void initImageLoader(Context context)
	{
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.

		DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder().considerExifParams(true)
				.resetViewBeforeLoading(false).cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
                .delayBeforeLoading(200)
                .displayer(new RoundedBitmapDisplayer(180))
				.build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
				.defaultDisplayImageOptions(defaultDisplayImageOptions).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.threadPoolSize(3)
				.memoryCache(new UsingFreqLimitedMemoryCache(5 * 1024 * 1024))
				// You can pass your own memory cache
				// implementation/你可以通过自己的内存缓存实现
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024)
				// 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO).writeDebugLogs() // Remove
				// for
				// release
				// app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}
}
