package cgmblelib.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.location.LocationManager;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.os.StatFs;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

import cgmblelib.database.entity.PocGlucose;
import androidx.annotation.NonNull;

/**
 * Created by chumming on 2018/3/23.
 * 基础工具类
 * notNull(Object ...objects)  不为 null 的判断
 * notEmpty(String ...strings) 不为 空 的判断
 * getAppPackageName(Context context) 获取APP包名字
 *
 * @author minyuchun
 */
public class Tool {
    /**
     * yyyy-MM-dd HH:mm:ss
     */
    private static final SimpleDateFormat SDF2 = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

    private static final ThreadLocal<DateFormat> SDF = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        }
    };

    /***
     * 构造函数
     */
    private Tool() {
        throw new UnsupportedOperationException("U can't instantiate Tool");
    }


    /**
     * 获取APP包名字
     *
     * @param context 上下文
     * @return 返回包名
     */
    public static String getAppPackageName(Context context) {
        if (context != null) {
            return context.getPackageName();
        }
        return null;
    }

    /**
     * 获取小数点后一位小数
     *
     * @param value 值
     * @return 四舍五入的值
     */
    public static float getDecimalOneNumber(float value) {
        try {
            return BigDecimal.valueOf(value).setScale(1, RoundingMode.HALF_UP).floatValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0.0f;
    }

    /**
     * 获取小数点后一位小数
     *
     * @param value 值
     * @return 四舍五入的值
     */
    public static float getDecimalTwoNumber(float value) {
        try {
            return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP).floatValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取String类型的血糖显示值,
     * 大部分数值经过转换可以很好的显示值，但是当数值为整数时,部分小数点后一位小数就有点欠缺
     *
     * @return 处理过后的数
     */
    public static String getStringGluValue(float value) {
        return String.valueOf(getDecimalOneNumber(value));
    }

    /**
     * 数值相加
     *
     * @param a 数值a
     * @param b 数值b
     * @return 返回的数值 BigDecimal
     */
    public static BigDecimal add(float a, float b) {
        return BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
    }

    /**
     * 数值相除
     *
     * @param a 数值a
     * @param b 数值b
     * @return 返回相除的数值 BigDecimal
     */
    public static BigDecimal divide(float a, float b) {
        return BigDecimal.valueOf(a).divide(BigDecimal.valueOf(b), 2, RoundingMode.HALF_UP);
    }

    /**
     * 将 date日期转成成 所属格式后
     *
     * @param date       日期
     * @param dateFormat 日期转换格式
     * @return 返回String日期
     */
    public static String getFormatDate(Date date, @NonNull String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat, Locale.getDefault());
        return date != null ? format.format(date) : "";
    }

    /***
     * 将String string yyyy-MM-dd HH:mm:ss 日期转化成data类型的日期
     * @param date String 类型
     * @return 返回data类型
     */
    public synchronized static Date getParseDate(String date) {
        try {
            int count = date.split(":").length - 1;
            if (count > 1) {
                return Objects.requireNonNull(SDF.get()).parse(date);
            } else {
                return SDF2.parse(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date1 = new Date();
        MyLog.i("getParseDate-return date" + date1.toString());
        return date1;
    }

    /***
     * 将年月日时间
     * @return Calendar时间
     */
    public static Calendar getTime(int year, int month, int day, int hourOfDay, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, hourOfDay, minute, 0);
        return calendar;
    }

    /**
     * 是否在同步数据的流程
     *
     * @param glucose 数据
     * @return 是否正在同步数据
     */
    public static boolean isPullData(PocGlucose glucose) {
        if (glucose != null && glucose.getBytes() != null && glucose.getBytes().length > 0) {
            byte start = glucose.getBytes()[0];
            return start == 0x47 || start == 0x08 || start == 0x0C || start == 0x0D || start == 0x22;
        }
        return false;
    }

    /***
     * 获取文件 /data/data/youPackageName
     * @param context 上下文
     * @return 文件
     */
    public static File getAppDir(Context context) {
        File cacheDir = context.getCacheDir();
        if (cacheDir != null) {
            return context.getCacheDir().getParentFile();
        }
        return cacheDir;
    }

    /**
     * 获取剩余容量的大小
     *
     * @param file 文件
     * @return 返回剩余大小 单位M
     */
    public static long getAvailableSize(@NonNull File file) {
        StatFs dataStat = new StatFs(file.getPath());
        long blockSize = dataStat.getBlockSizeLong();
        long availableBlocks = dataStat.getAvailableBlocksLong();
        return blockSize * availableBlocks;
    }

    /**
     * 是否是debug版本
     *
     * @param context 上下文
     * @return 是否是debug
     */
    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 系统蓝牙是否可用
     *
     * @return true 可用
     */
    public static boolean isBluetoothEnabled(Context context) {
        BluetoothAdapter adapter = getBluetoothAdapter(context);
        return adapter != null && adapter.isEnabled();
    }

    /**
     * 开启 或者 关闭 系统蓝牙
     *
     * @return true 操作成功，false 操作失败
     */
    @SuppressLint("MissingPermission")
    public static void ableBluetooth(Activity activity, int requestCode) {
        BluetoothAdapter adapter = getBluetoothAdapter(activity);
        if (adapter != null && !adapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, requestCode);
        }
    }

    /**
     * 获取蓝牙适配器
     *
     * @param context 上下文
     * @return 返回蓝牙适配器
     */
    public static BluetoothAdapter getBluetoothAdapter(Context context) {
        BluetoothAdapter adapter = null;
        if (context != null) {
            BluetoothManager mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager != null) {
                adapter = mBluetoothManager.getAdapter();
            }
        }
        if (adapter == null) {
            adapter = BluetoothAdapter.getDefaultAdapter();
        }
        return adapter;
    }

    /**
     * GPS是否可用
     *
     * @param context 上下文
     * @return true 可用
     */
    public static boolean isGpsEnable(Context context) {
        if (context != null) {
            LocationManager locationManager = ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE));
            if (locationManager != null) {
                return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            }
        }
        return false;
    }

    /**
     * 在 S(12) 及以上的版本搜索蓝牙设备的时候不需要在进行local权限的判断
     * @param context 上下文
     * @return true 表示不需要去判断或者GPS已经打开
     */
    public static boolean isGPSEnable_S(Context context){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S){
            return isGpsEnable(context);
        }
        return true;
    }

    public static boolean isInMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    //选择时间范围弹框选项
    public static synchronized int getHour(long currentTime) {
        Calendar tempStart = Calendar.getInstance();
        tempStart.clear();
        tempStart.setTimeInMillis(currentTime);
        return tempStart.get(Calendar.HOUR_OF_DAY);
    }

    //选择时间范围弹框选项
    public static synchronized int getMinute(long currentTime) {
        Calendar tempStart = Calendar.getInstance();
        tempStart.clear();
        tempStart.setTimeInMillis(currentTime);
        return tempStart.get(Calendar.MINUTE);
    }

    /**
     * 获取旋转动画
     *
     * @return 返回旋转动画
     */
    public static RotateAnimation getRotate() {
        RotateAnimation rotateAnimation = new RotateAnimation(0f, 359f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        LinearInterpolator lin = new LinearInterpolator();
        rotateAnimation.setInterpolator(lin);
        rotateAnimation.setDuration(2000);
        rotateAnimation.setRepeatCount(-1);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setStartOffset(0);
        return rotateAnimation;
    }

    public static ScaleAnimation getTrans() {
        ScaleAnimation rotateAnimation = new ScaleAnimation(1f, 1f, 0, 1, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f);
        rotateAnimation.setDuration(300);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setStartOffset(0);
        return rotateAnimation;
    }

    public static ScaleAnimation getTransHind() {
        ScaleAnimation rotateAnimation = new ScaleAnimation(1f, 1f, 1, 0, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f);
        rotateAnimation.setDuration(300);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setStartOffset(0);
        return rotateAnimation;
    }

    /**
     * 将 秒数据 转换成 时:分
     *
     * @param value 秒总数
     * @return 时:分
     */
    public static String secondsToFormatTimeString(long value) {
        String finalTimerString = "";
        int hours, minutes, seconds;
        hours = (int) (value / (60 * 60));
        minutes = (int) (value % (60 * 60)) / (60);
        seconds = (int) ((value % (60 * 60)) % (60));
        finalTimerString = String.format(Locale.ENGLISH, "%02d:%02d:%02d", hours, minutes, seconds);
        return finalTimerString;
    }

    public static boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0];
            //得到输入框在屏幕中上下左右的位置
            int top = l[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    public static void hideKeyboard(Activity context, IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
