package com.yyrh.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.provider.Settings;
import android.util.Base64;
import android.util.Log;

import com.yyrh.constant.SDKSettings;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Utils {

    public static final String TAG = "Utils";


    public static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);

    }


    public static String getDeviceVersion() {
        try {
            return Build.VERSION.RELEASE;
        } catch (Exception e) {
            return "";
        }

    }

    public static String getDeviceModel() {
        try {
            return Build.MODEL;
        } catch (Exception e) {
            return "";
        }

    }


    public static String getMD5(String content) {
        String s = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(content.getBytes());
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);

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


    /**
     * 解码
     *
     * @param paramString
     * @return string
     */
    public static String decoBase64(String paramString) {
        if (paramString == null || paramString.equals("")) {
            return "";
        }

        try {

            String strBase64 = new String(Base64.decode(paramString.getBytes(),
                    Base64.NO_WRAP));
            // String strBase64 = new String(paramString.getBytes(),
            // Base64.DEFAULT);
            // str = URLDecoder.decode(paramString, "UTF-8");
            return strBase64;
        } catch (Exception localException) {
            System.out.println("toURLDecoded error:" + paramString + ","
                    + localException);
        }

        return "";
    }

    public static String readAssertFileWithKey(Context context, String file_name, String key) {
        String web_str = "";

        InputStream input_stream = null;
        try {
            input_stream = context.getAssets().open(file_name);


            InputStreamReader inputStreamReader = new InputStreamReader(
                    input_stream);

            BufferedReader reader = new BufferedReader(inputStreamReader);

            String tempString = null;

            while ((tempString = reader.readLine()) != null) {

                if (tempString.contains(key)) {

                    web_str = tempString.substring(tempString.indexOf("=") + 1,
                            tempString.length());
                    break;
                }
            }
            reader.close();
        } catch (IOException e) {
            YYLog.i(file_name + " does not exist in assets");
        }

        return web_str;
    }

    public static String getParamCnfValuebyKey(Context context,
                                               String filename, String key) {

        return Utils.readAssertFileWithKey(context, filename, key);

    }

    public static String GetApplicationMetaData(Context context, String metaName) {
        Object metaData = "";

        if (null == metaName || metaName.isEmpty()) {
            Log.e(TAG, "metaName is empty when call GetApplicationMetaData");
            return "";
        }
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            metaData = info.metaData.get(metaName);
            // 是否有引用
            if (null != metaData && metaData.toString().contains("ref=")) {
                String newMetaName = metaData.toString().split("=")[1];
                metaData = GetApplicationMetaData(context, newMetaName);
            }
        } catch (NameNotFoundException e) {
            Log.e(TAG, "must config application meta data : " + metaName);
        }
        if (null == metaData) {
            metaData = "";
        }
        return metaData.toString();
    }


    public static boolean judgeStrNull(String str) {
        return (str == null || str.equals(""));
    }

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    /**
     * check this obj
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> T checkNotNull(T obj) {
        if (obj == null) {
            throw new NullPointerException();
        }
        return obj;
    }


    public static String getSharedPreferences(Context context, String tag,
                                              String key) {

        SharedPreferences sp = context.getSharedPreferences(tag,
                Activity.MODE_PRIVATE);
        String name = sp.getString(key, "");
        return name;

    }

    public static String getPackageName(Activity ac) {

        String pkgName = ac.getPackageName();
        return pkgName;
    }


    public static void setSharedPreferences(String head, String key, String value, Context context) {
        SharedPreferences sp = context.getSharedPreferences(head, Activity.MODE_PRIVATE);
        // 实例化SharedPreferences.Editor对象（第二步）l
        SharedPreferences.Editor editor = sp.edit();
        // 用putString的方法保存数据
        editor.putString(key, value);
        // 提交当前数据
        editor.commit();
    }

    public static void setSharedPreferences(String head, Map<String, String> data, Context context) {
        SharedPreferences sp = context.getSharedPreferences(head, Activity.MODE_PRIVATE);
        // 实例化SharedPreferences.Editor对象（第二步）l
        SharedPreferences.Editor editor = sp.edit();
        // 用putString的方法保存数据

        for (String key : data.keySet()) {
            editor.putString(key, data.get(key));
        }


        // 提交当前数据
        editor.commit();
    }

    /*
     * 获取SharedPreferences
     */

    public static String getSharedPreferences(String head, String key, Context context) {
        SharedPreferences sp = context.getSharedPreferences(head, Activity.MODE_PRIVATE);
        String value = sp.getString(key, "");
        return value;
    }
    /*
     * 获取versionName
     */

    public static String getVersionName(Context context) {
        String pkName = context.getPackageName();
        try {

            String versionName = context.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            return versionName;

        } catch (Exception e) {
        }
        return "";
    }

    public static String getApplicationName(Activity activity) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = activity.getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(activity), 0);
        } catch (NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName =
                (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    public static boolean getTextIsNull(String text) {
        if (text.equals("") || text == null) {
            return true;
        }
        return false;
    }


    public static String getRandom(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }


    public static String getUserCententerUrl(String operation, HashMap<String, String> map) {

        String params = "";
        for (String key : map.keySet()) {

            params = params + key + "=" + map.get(key) + "&";
        }

        return SDKSettings.UserCentUrl + operation + params.substring(0, params.length() - 1);
    }

    public static boolean isLandscape(Activity activity) {
        int orientation = activity.getRequestedOrientation();
        return orientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT &&
                orientation != ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    }
}