package com.imofan.android.basic;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import java.util.TimeZone;
import java.util.UUID;

/**
 * 应用及手机信息封装类
 */
public class MFStatInfo {
    private final static String LOG_TAG = Mofang.LOG_TAG + "_MFStatInfo";

//    static TelephonyManager telephonyManager = null;
//    static DisplayMetrics displayMetrics = null;
//    static ConnectivityManager connectivityManager = null;

    private static SharedPreferences sp = null;
    private static SharedPreferences.Editor spEditor = null;
    public final static String INFO_FILE = "mofang_data_analysis";     //SharedPreferences文件名称
    final static String KEY_INSTALL_DATE = "install_date";
    public final static String KEY_DEV_ID = "dev_id";
    final static String KEY_DEV_ID_UNDEFINED = "dev_id_udf";
    public final static String KEY_APP_VERSION = "app_ver";
    final static String KEY_SDK_VERSION = "sdk_ver";
    final static String KEY_CHANNEL = "channel";
    final static String KEY_OS = "os";
    public final static String KEY_OS_VERSION = "os_ver";
    final static String KEY_CARRIER = "carrier";
    final static String KEY_RESOLUTION = "resolution";
    public final static String KEY_MODEL = "model";
    final static String KEY_TIMEZONE = "timezone";
    final static String KEY_LANGUAGE = "language";
    final static String KEY_COUNTRY = "country";
    final static String KEY_DEVICE_ID = "device_id";
    final static String KEY_MAC_ADDRESS = "mac_addr";
    final static String KEY_USER_RETURN = "user_return";
    final static String KEY_USER_ACCESS_PATH = "user_activities";
    final static String KEY_USER_PAUSE_TIME = "user_pause_time";
    final static String KEY_USER_DURATION = "user_duration";
    final static String KEY_LATEST_SENDT_TIME = "latest_send_time";

    static synchronized void init(Context context) {
        if(sp == null) {
            sp = context.getSharedPreferences(INFO_FILE, 0);
            spEditor = sp.edit();
        }
    }

    //判断设备信息是否更新，并记录更新 负责初始化设备信，同时负责初始化设备信息
    static void updateAppAndDeviceInfo(MFDatabaseManager dbManager,Context activity, int date, int hour) {
        //设备ID
        String deviceId = "";
        TelephonyManager telephonyManager = null;
        try {
            telephonyManager = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
            deviceId = telephonyManager.getDeviceId().toLowerCase();
            if(deviceId.equals("000000000000000")) {
                deviceId = "";
            }
            MFStatInfo.putString(MFStatInfo.KEY_DEVICE_ID, deviceId);
        } catch (Exception e) {

        }

        //设备型号
        MFStatInfo.putString(MFStatInfo.KEY_MODEL, Build.MODEL);

        
        //分辨率
        DisplayMetrics displayMetrics = activity.getResources()
				.getDisplayMetrics();
        //DisplayMetrics displayMetrics = new DisplayMetrics();
//        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        MFStatInfo.putString(MFStatInfo.KEY_RESOLUTION, displayMetrics.heightPixels + "x" + displayMetrics.widthPixels);

        //应用安装日期、判断是否回头用户
        int installDate = MFStatInfo.getInt(MFStatInfo.KEY_INSTALL_DATE, 0);
        if(installDate <= 0) {
            installDate = date;
            MFStatInfo.putInt(MFStatInfo.KEY_INSTALL_DATE, installDate);
        } else {
            //判断曾经是否是回头用户
            boolean isReturnUser = MFStatInfo.getBoolean(MFStatInfo.KEY_USER_RETURN, false);
            //如果曾经不是回头用户
            if(!isReturnUser) {
                if(date > installDate) {   //是回头用户
                    //生成回头用户事件
                    MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_RETURN_USER, date, hour, null);

                    //记录已为回头用户
                    MFStatInfo.putBoolean(MFStatInfo.KEY_USER_RETURN, true);
                }
            }
        }

        //魔方SDK版本信息
        String sdkVersion = MFStatInfo.getString(MFStatInfo.KEY_SDK_VERSION, null);
        if(!Mofang.SDK_VERSION.equals(sdkVersion)) {
            MFStatInfo.putString(MFStatInfo.KEY_SDK_VERSION, Mofang.SDK_VERSION);
            if(sdkVersion != null) {
                MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_SDK_VERSION);
            }
        }

        //应用版本、判断是否新装或更新应用
        String oldAppVersion = MFStatInfo.getString(MFStatInfo.KEY_APP_VERSION, null);
        String appVersion = null;
        try {
            PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(
                        activity.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            appVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(LOG_TAG, "[updateAppAndDeviceInfo]Get app version error");
            e.printStackTrace();
        }
        if(oldAppVersion == null) {     //新装应用
            //生成新装应用事件
            MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_INSTALL, date, hour, appVersion);
            //修改应用信息
            MFStatInfo.putString(MFStatInfo.KEY_APP_VERSION, appVersion);
            MFStatInfo.putInt(MFStatInfo.KEY_INSTALL_DATE, date);
        } else if(appVersion != null && !appVersion.equals(oldAppVersion)) {
            //生成应用更新事件
            MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPGRADE, date, hour, oldAppVersion);
            //生成设备信息更新事件
            MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_APP_VERSION);
            //修改应用信息
            MFStatInfo.putString(MFStatInfo.KEY_APP_VERSION, appVersion);
            //清除旧版本应用的访问路径数据
            MFStatInfo.putString(MFStatInfo.KEY_USER_ACCESS_PATH, "");
            MFStatEvent.clearAccessPath(dbManager);
        }

        //发布渠道版本
        String channel = MFStatInfo.getString(MFStatInfo.KEY_CHANNEL, null);
        if(channel == null) {
            try {
                channel = (String)activity.getPackageManager().getApplicationInfo(activity.getPackageName(),
                        PackageManager.GET_META_DATA).metaData.get("MOFANG_CHANNEL");
                MFStatInfo.putString(MFStatInfo.KEY_CHANNEL, channel);
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(LOG_TAG, "[updateAppAndDeviceInfo]Get app channel error");
                e.printStackTrace();
            }
        }

        //操作系统版本
        String oldOsVersion = MFStatInfo.getString(MFStatInfo.KEY_OS_VERSION, null);
        String osVersion = Build.VERSION.RELEASE;
        if(osVersion != null && !osVersion.equals(oldOsVersion)) {
            MFStatInfo.putString(MFStatInfo.KEY_OS_VERSION, osVersion);
            if(oldOsVersion != null) {
                MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_OS_VERSION);
            }
        }

        //运营商
        String oldCarrier = MFStatInfo.getString(MFStatInfo.KEY_CARRIER, null);
        String carrier = null;
        if(telephonyManager != null) {
            String imsi = telephonyManager.getSubscriberId();
            if(imsi != null && imsi.trim().length() > 0) {
                if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
                    carrier = "中国移动";
                } else if (imsi.startsWith("46001")) {
                    carrier = "中国联通";
                } else if (imsi.startsWith("46003")) {
                    carrier = "中国电信";
                } else {
                    carrier = telephonyManager.getSimOperatorName();
                }
                if(carrier != null && !carrier.equals(oldCarrier)) {
                    MFStatInfo.putString(MFStatInfo.KEY_CARRIER, carrier);
                    if(oldCarrier != null) {
                        MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_CARRIER);
                    }
                }
            }
        }

        //时区
        int oldTimezone = MFStatInfo.getInt(MFStatInfo.KEY_TIMEZONE, 8);
        int timezone = TimeZone.getDefault().getRawOffset()/(60*60*1000);
        if(timezone != oldTimezone) {
            MFStatInfo.putInt(MFStatInfo.KEY_TIMEZONE, timezone);
            MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_TIMEZONE);
        }

        //语言
        String oldLanguage = MFStatInfo.getString(MFStatInfo.KEY_LANGUAGE, null);
        String language = activity.getResources().getConfiguration().locale.getDisplayLanguage();
        if(language != null && !language.equals(oldLanguage)) {
            MFStatInfo.putString(MFStatInfo.KEY_LANGUAGE, language);
            if(oldLanguage != null) {
                MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_LANGUAGE);
            }
        }

        //国家
        String oldCountry = MFStatInfo.getString(MFStatInfo.KEY_COUNTRY, null);
        String country = activity.getResources().getConfiguration().locale.getCountry();
        if(country != null && !country.equals(oldCountry)) {
            MFStatInfo.putString(MFStatInfo.KEY_COUNTRY, country);
            if(oldCountry != null) {
                MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_UPDATE, date, hour, MFStatInfo.KEY_COUNTRY);
            }
        }

        //DEV-ID，需要ACCESS_WIFI_STATE权限
        String devId = MFStatInfo.getString(MFStatInfo.KEY_DEV_ID, null);
        if(devId == null || devId.length() != 32) {
            //获取WiFi Mac地址
            WifiManager wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String mac = (info == null) ? "" : (info.getMacAddress() == null ? "" : info.getMacAddress())
                    .replaceAll(":", "").toLowerCase();
            MFStatInfo.putString(MFStatInfo.KEY_MAC_ADDRESS, mac);
            //序列号
//            String serialnum = "";
//            try {
//                Class<?> c = Class.forName("android.os.SystemProperties");
//                Method get = c.getMethod("get", String.class, String.class );
//                serialnum = (String)(get.invoke(c, "ro.serialno", ""));
//            } catch (Exception ignored) {
//
//            }
            //生成身份指纹
//            String sum = deviceId + "-" + mac + "-" + serialnum;
            String sum = deviceId + "-" + mac;
            if(sum.length() > 1) {
                sum = "dev-" + sum;
                if(Mofang.DEBUG) {
                    Log.d(LOG_TAG, "[updateAppAndDeviceInfo]devIdSum = " + sum);
                }
//                try {
//                    MessageDigest md5Encoder = MessageDigest.getInstance("MD5");
//                    byte[] md5Bytes = md5Encoder.digest(sum.getBytes());
//                    StringBuilder md5Hex = new StringBuilder();
//                    for (byte b : md5Bytes) {
//                        String hex = Integer.toHexString(0xFF & b);
//                        if(hex.length() < 2) {
//                            md5Hex.append("0");
//                        }
//                        md5Hex.append(hex);
//                    }
//                    devId = md5Hex.toString().toLowerCase();
//                } catch (NoSuchAlgorithmException e) {
//                    e.printStackTrace();
//                }
                MFStatInfo.putInt(MFStatInfo.KEY_DEV_ID_UNDEFINED, 0);
            } else {
                sum = "udf-" + Build.MODEL + "-" + (osVersion == null ? "" : osVersion) + "-"
                        + (carrier == null ? "" : carrier) + "-" + System.currentTimeMillis() + "-" + Math.random();
                if(Mofang.DEBUG) {
                    Log.d(LOG_TAG, "[updateAppAndDeviceInfo]devIdSum = " + sum);
                }
                MFStatInfo.putInt(MFStatInfo.KEY_DEV_ID_UNDEFINED, 1);
            }
            devId = UUID.nameUUIDFromBytes(sum.getBytes()).toString().replaceAll("-", "");
            MFStatInfo.putString(MFStatInfo.KEY_DEV_ID, devId);
        } else {
            MFStatInfo.putInt(MFStatInfo.KEY_DEV_ID_UNDEFINED, 0);
        }
    }

    static void putString(String key, String value) {
        spEditor.putString(key, value);
        spEditor.commit();
        if(Mofang.DEBUG) {
            Log.d(LOG_TAG, "[putString]{" + key + ", " + value + "}");
        }
    }

    public static String getString(String key, String def) {
    	if(null!=sp){
    		return sp.getString(key, def);
    	}
    	return "";
    }

    static void putInt(String key, int value) {
        spEditor.putInt(key, value);
        spEditor.commit();
        if(Mofang.DEBUG) {
            Log.d(LOG_TAG, "[putInt]{" + key + ", " + value + "}");
        }
    }

    static int getInt(String key, int def) {
        return sp.getInt(key, def);
    }

    static void putLong(String key, long value) {
        spEditor.putLong(key, value);
        spEditor.commit();
        if(Mofang.DEBUG) {
            Log.d(LOG_TAG, "[putLong]{" + key + ", " + value + "}");
        }
    }

    static long getLong(String key, long def) {
        return sp.getLong(key, def);
    }

//    static void putFloat(String key, float value) {
//        spEditor.putFloat(key, value);
//        spEditor.commit();
//        if(Mofang.DEBUG) {
//            Log.d(LOG_TAG, "[putFloat]{" + key + ", " + value + "}");
//        }
//    }
//
//    static float getFloat(String key, float def) {
//        return sp.getFloat(key, def);
//    }

    static void putBoolean(String key, boolean value) {
        spEditor.putBoolean(key, value);
        spEditor.commit();
        if(Mofang.DEBUG) {
            Log.d(LOG_TAG, "[putBoolean]{" + key + ", " + value + "}");
        }
    }

    static boolean getBoolean(String key, boolean def) {
        return sp.getBoolean(key, def);
    }
}
