/**
 * ClassName: MyApp.java
 * created on 2013-1-24
 * Copyrights 2013-1-24 hjgang All rights reserved.
 * site: http://t.qq.com/hjgang2012
 * email: hjgang@yahoo.cn
 */
package com.shunzhi.parent.util;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;

import com.shunzhi.parent.R;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import timber.log.Timber;


/**
 * 获取系统信息的工具类
 *
 * @author hjgang
 */
public class SystemHelper {
    private SystemHelper() {
    }

    /**
     * 创建本应用的桌面快捷方式<br/>
     * 注意:需要添加权限&lt;uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/&gt;
     *
     * @param
     */
    public static void createShortcut(Context context, Class<?> clazz) {
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

        //快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
        shortcut.putExtra("duplicate", false); //不允许重复创建

        Intent localIntent2 = new Intent(context, clazz);
        localIntent2.setAction(Intent.ACTION_MAIN);
        localIntent2.addCategory(Intent.CATEGORY_LAUNCHER);

        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, localIntent2);//指定快捷方式要启动的Activity类型

        //快捷方式的图标
        ShortcutIconResource iconResource = ShortcutIconResource.fromContext(context, R.drawable.logo);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);

        context.sendBroadcast(shortcut);
    }

    /**
     * 字符串转换成date
     *
     * @param time
     * @return
     */
    public static Date getDateTime1(String time) {
        Date newtime = null;
        SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            if (time != null && !time.equals("0")) {
                newtime = sdfDateFormat.parse(time);
            }
        } catch (Exception err) {

        }
        return newtime;
    }

    /**
     * 将字符串转为  时间戳
     *
     * @param time
     * @return
     */
    public static String getTimestamp(String time) {
        Date newtime = null;
        SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            if (time != null && !time.equals("0")) {
                newtime = sdfDateFormat.parse(time);
            }
        } catch (Exception err) {

        }
        return newtime.getTime() + "";
    }

    /**
     * 将时间戳转为 字符串
     * yyyy-MM-dd HH:mm
     */
    public static String getTimeStr(String time) {

        String newtime = null;
        SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (time != null && !time.equals("0")) {
            newtime = sdfDateFormat.format(new Timestamp(Long.parseLong(time)));
        }
        return newtime;
    }

    /**
     * 将时间戳转为 字符串
     * yyyy-MM-dd
     */
    public static String getTimeStr3(String time) {
        String newtime = null;
        SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (time != null && !time.equals("0")) {
            newtime = sdfDateFormat.format(new Date(Long.parseLong(time) * 1000));
        }
        return newtime;
    }

    // 将字符串转为时间戳
    public static String getTime(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日hh时mm分");
        Date date = null;
        if (time == null || "".equals(time) || "null".equals(time)) {
            return "0";
        }
        if (time.contains("年")) {
            int year = Integer.parseInt(time.substring(0, time.indexOf("年")));
            if (year <= 1970) {
                return "0";
            }
        }
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        return date.getTime() / 1000 + "";
    }

    // 将字符串转为时间戳
    public static String getTime2(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = null;
        if (time == null || "".equals(time) || "null".equals(time)) {
            return "0";
        }
        int year = Integer.parseInt(time.substring(0, time.indexOf("年")));
        if (year <= 1970) {
            return "0";
        }
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime() / 1000 + "";
    }

    /**
     * @param oldTime 较小的时间
     * @param newTime 较大的时间 (如果为空   默认当前时间 ,表示和当前时间相比)
     * @return -1 :同一天.    0:昨天 .   1 :至少是前天.
     * @throws ParseException 转换异常
     * @author LuoB.
     */
    public static int isYeaterday(Date oldTime, Date newTime) throws ParseException {
        if (newTime == null) {
            newTime = new Date();
        }
        //将下面的 理解成  yyyy-MM-dd 00:00:00 更好理解点
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = format.format(newTime);
        Date today = format.parse(todayStr);
        //昨天 86400000=24*60*60*1000 一天
        if ((today.getTime() - oldTime.getTime()) > 0 && (today.getTime() - oldTime.getTime()) <= 86400000) {
            return 0;
        } else if ((today.getTime() - oldTime.getTime()) <= 0) { //至少是今天
            return -1;
        } else { //至少是前天
            return 1;
        }
    }

    /**
     * 检查是否已经创建了桌面快捷方式<br/>
     * 注意:需要添加权限&lt;uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/&gt;
     *
     * @param context
     * @return
     */
    public static boolean hasShortCut(Context context) {
        String url = "";
        if (Build.VERSION.SDK_INT < 8) {
            url = "content://com.android.launcher.settings/favorites?notify=true";
        } else {
            url = "content://com.android.launcher2.settings/favorites?notify=true";
        }
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse(url), null, "title=?",
                new String[]{context.getString(R.string.app_name)}, null);

        if (cursor != null && cursor.moveToFirst()) {
            cursor.close();
            return true;
        }

        return false;
    }

    /**
     * 获取当前机器的屏幕信息对象<br/>
     * 另外:通过android.os.Build类可以获取当前系统的相关信息
     *
     * @param context
     * @return
     */
    public static DisplayMetrics getScreenInfo(Context context) {
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(dm);
        // dm.widthPixels;//寬度
        // dm.heightPixels; //高度
        // dm.density; //密度
        return dm;
    }

    public static int dip2px(Context context, double dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, double pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取手机号<br/>
     * 注意:需要添加权限&lt;uses-permission
     * android:name="android.permission.READ_PHONE_STATE"/&gt;。另外很多手机不能获取到当前手机号
     *
     * @param context
     * @return
     */
    public static String getMobileNumber(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
        }
        String deviceid = tm.getDeviceId();//获取智能设备唯一编号
        String te1 = tm.getLine1Number();//获取本机号码
        String imei = tm.getSimSerialNumber();//获得SIM卡的序号
        String imsi = tm.getSubscriberId();//得到用户Id
        return tm.getLine1Number();
    }

    /**
     * 检测当前的网络连接是否可用<br/>
     * 注意:需要添加权限&lt;uses-permission
     * android:name="android.permission.ACCESS_NETWORK_STATE"/&gt;
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        boolean flag = false;
        try {
            ConnectivityManager connManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null != connManager) {
                NetworkInfo info = connManager.getActiveNetworkInfo();
                if (null != info && info.isAvailable()) {
                    flag = true;
                }
            }
        } catch (Exception e) {
            Timber.d(e + "");
        }
        return flag;
    }

    /**
     * 检测当前网络连接的类型<br/>
     * 注意:需要添加权限&lt;uses-permission
     * android:name="android.permission.ACCESS_NETWORK_STATE"/&gt;
     *
     * @param context
     * @return 返回0代表GPRS网络;返回1,代表WIFI网络;返回-1代表网络不可用
     */
    public static int getNetworkType(Context context) {
        int code = -1;
        try {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null != connManager) {
                State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
                if (State.CONNECTED == state) {
                    code = ConnectivityManager.TYPE_WIFI;
                } else {
                    state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
                    if (State.CONNECTED == state) {
                        code = ConnectivityManager.TYPE_MOBILE;
                    }
                }
            }
        } catch (Exception e) {
            Timber.d(e + "");
        }
        return code;
    }

    /**
     * 返回当前程序版本代码,如:1
     *
     * @param context
     * @return 当前程序版本代码
     */
    public static int getAppVersionCode(Context context) {
        int versionCode = -1;
        try {
            PackageManager pm = context.getApplicationContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = pi.versionCode;

        } catch (Exception e) {
            Timber.d("66666%s", e.toString() + "");
        }
        return versionCode;
    }

    /**
     * 返回当前程序版本名,如:1.0.1
     *
     * @param context
     * @return 当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;

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

    /**
     * 安装指定的APK文件,主要用于本应用程序的更新
     *
     * @param context
     * @param apk     apk文件的全路径名
     */
    public static void installAPK(Context context, String apk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri data;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(context, "com.shunzhi.parent.fileprovider", new File(apk));
// 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else data = Uri.fromFile(new File(apk));

        intent.setDataAndType(data, "application/vnd.android.package-archive");
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static void remoteAPK(Context context) {
        Uri packageURI = Uri.parse("package:net.shunzhi");
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        context.startActivity(uninstallIntent);
    }

//    public static void setSystemBar(Context context, boolean on, int color) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            SystemHelper.setTranslucentStatus(context, on);
//            SystemBarTintManager mTintManager = new SystemBarTintManager((Activity) context);
//            mTintManager.setStatusBarTintEnabled(true);
//            //mTintManager.setNavigationBarTintEnabled(true);
//            mTintManager.setStatusBarTintResource(color);
//
//            //SystemBarTintManager.SystemBarConfig config = mTintManager.getConfig();
//            //listViewDrawer.setPadding(0, config.getPixelInsetTop(true), 0, config.getPixelInsetBottom());
//        }
//    }

    @TargetApi(19)
    public static void setTranslucentStatus(Context context, boolean on) {
        Window win = ((Activity) context).getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}