package com.tofly.ghrq_route.common.util.app;

import android.app.ActivityManager;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ParseException;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.mgq.base.utils.toast.ToastUtil;

import org.apache.http.HttpEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * Created by zombiexq on 2016/6/13.
 */
public class AppUtil {

    /* md5 加密 */
    public  static String md5 (String str) {
        MessageDigest algorithm = null;
        try {
            algorithm = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (algorithm != null) {
            algorithm.reset();
            algorithm.update(str.getBytes());
            byte[] bytes = algorithm.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : bytes) {
                hexString.append(Integer.toHexString(0xFF & b));
            }
            return hexString.toString();
        }
        return "";

    }
    /* 获取本地app版本*/
    public static int getLocalVersionCode(Context context){
        int version = 1;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /* 获取本地app版本*/
    public static String getLocalVersionName(Context context){
        String version = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /*获取设备编号*/
    public static String getDeviceId(Context context){
        try{
            TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        }catch (Exception e){
            e.printStackTrace();
            return"";
        }


    }

    /* 首字母大写 */
    static public String ucfirst (String str) {
        if (str != null && str != "") {
            str  = str.substring(0,1).toUpperCase()+str.substring(1);
        }
        return str;
    }

    /**
     * 判断邮箱是否合法
     * @param email
     * @return
     */
    public static boolean isEmail(String email){
        if (null==email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 判断手机号码是否合法
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
	    /*
	    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
	    联通：130、131、132、152、155、156、185、186
	    电信：133、153、180、189、（1349卫通）
	    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
	    */
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }


    /* 为 EntityUtils.toString() 添加 gzip 解压功能 */
    public static String gzipToString(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }
        InputStream instream = entity.getContent();
        if (instream == null) {
            return "";
        }
        // gzip logic start
        if (entity.getContentEncoding().getValue().contains("gzip")) {
            instream = new GZIPInputStream(instream);
        }
        // gzip logic end
        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
        }
        int i = (int)entity.getContentLength();
        if (i < 0) {
            i = 4096;
        }
        String charset = EntityUtils.getContentCharSet(entity);
        if (charset == null) {
            charset = defaultCharset;
        }
        if (charset == null) {
            charset = HTTP.DEFAULT_CONTENT_CHARSET;
        }
        Reader reader = new InputStreamReader(instream, charset);
        CharArrayBuffer buffer = new CharArrayBuffer(i);

        try {
            char[] tmp = new char[1024];
            int l;
            while((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    /* 为 EntityUtils.toString() 添加 gzip 解压功能 */
    public static String gzipToString(final HttpEntity entity)
            throws IOException, ParseException {
        return gzipToString(entity, null);
    }

    public static SharedPreferences getSharedPreferences (Context ctx) {
        return ctx.getSharedPreferences("com.tofly.routing.sp.global", Context.MODE_PRIVATE);
    }

    public static SharedPreferences getSharedPreferences (Service service) {
        return service.getSharedPreferences("com.tofly.routing.demos.sp.global", Context.MODE_PRIVATE);
    }










    /* 判断int是否为空 */
    static public boolean isEmptyInt (int v) {
        Integer t = new Integer(v);
        return t == null ? true : false;
    }

    /* 获取毫秒数 */
    public static long getTimeMillis () {
        return System.currentTimeMillis();
    }

    /* 获取耗费内存 */
    public static long getUsedMemory () {
        long total = Runtime.getRuntime().totalMemory();
        long free = Runtime.getRuntime().freeMemory();
        return total - free;
    }

    /* 读取并创建位图 */
    public static Bitmap createBitmap(String path, int w, int h) {
        try {
            File f = new File(path);
            if (f.exists() == false)
                return null;
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            // 这里是整个方法的关键，inJustDecodeBounds设为true时将不为图片分配内存
            BitmapFactory.decodeFile(path, opts);
            int srcWidth = opts.outWidth;// 获取图片的原始宽度
            int srcHeight = opts.outHeight;// 获取图片原始高度
            int destWidth = 0;
            int destHeight = 0;
            // 缩放的比例
            double ratio = 0.0;
            if (srcWidth < w || srcHeight < h) {
                ratio = 0.0;
                destWidth = srcWidth;
                destHeight = srcHeight;
            } else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小
                ratio = (double) srcWidth / w;
                destWidth = w;
                destHeight = (int) (srcHeight / ratio);
            } else {
                ratio = (double) srcHeight / h;
                destHeight = h;
                destWidth = (int) (srcWidth / ratio);
            }
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放
            newOpts.inSampleSize = (int) ratio + 1;
            // inJustDecodeBounds设为false表示把图片读进内存中
            newOpts.inJustDecodeBounds = false;
            // 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
            newOpts.outHeight = destHeight;
            newOpts.outWidth = destWidth;
            // 获取缩放后图片
            return BitmapFactory.decodeFile(path, newOpts);
        } catch (Exception e) {
            return null;
        }
    }

    public static void hideKeyboard(Context context, View view){
        InputMethodManager methodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (view.isFocused()){
            methodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            view.clearFocus();
        }
    }

    public static boolean isServiceStarted(Context context, String className){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceInfos = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (serviceInfos == null || serviceInfos.size() <= 0)
            return false;

        for (ActivityManager.RunningServiceInfo serviceInfo : serviceInfos){
            if (className.equals(serviceInfo.service.getClassName())){
                return true;
            }
        }
        return false;
    }

    /**
     * 根据strings.xml中两个字符数组，组成一个键值对类型的Map,字符数组的长度必须相同
     * @param context
     * @param keyArrayResId     存放key的数组
     * @param valueArrayResId   存放value的数组
     * @return
     */
    public static Map<String, String> getMapFromStringArray(Context context, int keyArrayResId, int valueArrayResId){
        Map<String, String> keyValueMap = new HashMap<>();
        String[] keyArray = context.getResources().getStringArray(keyArrayResId);
        String[] valueArray = context.getResources().getStringArray(valueArrayResId);
        if (keyArray.length == valueArray.length){
            for (int i = 0; i < keyArray.length; i++){
                String key = keyArray[i];
                String value = valueArray[i];
                keyValueMap.put(key, value);
            }
        }
        return keyValueMap;
    }

    public static boolean isOutOfDate(String strDateBegin, String strDateEnd ) {
        boolean isOutOfDate = false;
        if (strDateBegin != null && strDateEnd != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = sdf.parse(strDateBegin);
                Calendar calendarBegin = Calendar.getInstance();
                calendarBegin.setTime(date);

                date = sdf.parse(strDateEnd);
                Calendar calendarEnd = Calendar.getInstance();
                calendarEnd.setTime(date);

                Calendar nowCalendar = Calendar.getInstance();
                if (nowCalendar.before(calendarBegin) || nowCalendar.after(calendarEnd))
                    isOutOfDate = true;

            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
        }
        return isOutOfDate;
    }

    public static void gotoSystemHome(Context context) {
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        homeIntent.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(homeIntent);
    }

    public static void hideSoftInput(Dialog dialog) {
        Window window = dialog.getWindow();
        if (window != null)
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    /**
     * 拨打电话
     * */
    public static void startPhoneCall(Context context, String mobile) {
        if (mobile != null && !mobile.isEmpty()) {
            String uri = "tel:" + mobile;
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            context.startActivity(intent);
        } else {
            ToastUtil.showToast(context, "用户电话不存在或无效");
        }
    }
}
