package com.ifavine.pay.common;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;


import com.ifavine.pay.ui.base.BaseApplication;

import com.ifavine.pay.utils.SPUtil;

import com.ifavine.pay.vo.User;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.List;
import java.util.Stack;


/**
 * Created by tree on 7/4/2016.
 */
public class AppContext extends BaseApplication {


    private static AppContext instance;


    public static User mUser;
    private HashSet<String> Msgs = new HashSet<>();

    /**
     * FONT_USE 发布时候要改为true
     */
    public static final boolean FontUse = true;
    /**
     * 是否调试模式
     */
    public static final boolean DebugModel = true;
    /**
     * 语言头部分
     */
    public static String AcceptLanguage = "cn";


    /**
     * 系统版本
     */
    public static String sAppVersionLocal = "1.0.0";
    /**
     * 服务端系统版本
     */
    public static String sAppVersionServer = "1.0.0";
    public static String sAppDownloadUrl;

    public static String sAppVersionDesc;

    /**
     * 手机系统版本
     */
    public static String sModileOsVersion = "android_4.2";

    /**
     * 手机型号
     */
    public static String sMobileOsModel = "MOBILE";

    /**
     * 经度
     */
    public static double sLongtitude;
    /**
     * 纬度
     */
    public static double sLatitude;


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
    }

    private void init() {

        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));

        //Bugly
        Context context = getApplicationContext();
        //// 获取当前包名
        String packageName = context.getPackageName();
        //// 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());


        getCurrentAppVer();

        ZXingLibrary.initDisplayOpinion(this);
    }


    /**
     * 获得当前app运行的AppContext
     */
    public static AppContext getInstance() {
        return instance;
    }


    /**
     * 获取App安装包信息
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null) info = new PackageInfo();
        return info;
    }


    public boolean isMainProcess() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public void getCurrentAppVer() {
        // 获取系统版本
        try {
            Log.i("aaaaa", "SDK_INT:" + Build.VERSION.SDK_INT);
            PackageManager pm = getPackageManager();// context为当前Activity上下文
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            sAppVersionLocal = pi.versionName;
            sAppVersionServer = pi.versionName;

            sModileOsVersion = Build.VERSION.RELEASE; // 获取版本号
            sMobileOsModel = Build.MODEL; // 获取手机型号

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


    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public static String getExcptionName(Throwable e) {
        String msg = e.toString();
        if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
            msg = "请求数据超时,请稍后重试";
        } else if (e instanceof ConnectException) {
            msg = "网络中断,请检查您的网络状态";
        } else if (e instanceof JsonSyntaxException) {
            msg = e.toString();
        }

        return msg;
    }

    // 记录打开的Activity
    public static Stack<Activity> Acts = new Stack<Activity>();

    public static void addActivity(Activity activity) {
        Acts.add(activity);
    }

    public static void removeActivity(Activity activity) {
        Acts.remove(activity);
    }

    public static void finishAllActivity() {
        for (Activity activity : Acts) {
            activity.finish();
        }
    }

    public static void exitApp() {
        finishAllActivity();
        System.exit(0);
    }

    /**
     * 获得登录用户的信息
     */
    public User getUser() {
        if (mUser == null) {
            String data = SPUtil.getInstance().readString("UserData");
            if (data != null) {
                Gson gson = new Gson();
                mUser = gson.fromJson(data, User.class);
            }
        }
        return mUser;
    }

    public void saveUser(User user) {
        mUser = user;
        Gson gson = new Gson();
        String data = gson.toJson(user);
        Log.i("aaaaa", "saveUser:" + data);
        SPUtil.getInstance().writeString("UserData", data);
    }

    public void setProperty(String key, String value) {
        if (value == null) {
            return;
        }
        AppConfig.getAppConfig(this).set(key, value);
    }

    /**
     * 获取cookie时传AppConfig.CONF_COOKIE
     */
    public String getProperty(String key) {
        String res = AppConfig.getAppConfig(this).get(key);
        return res;
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }


    Handler handler = new Handler();


}
