package tech.starwin.utils.format_utils;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import tech.starwin.R;

/**
 * Created by SiKang on 2018/10/16.
 * 时间、货币、String、Bean 格式化工具
 */
public class StringFormat {

    /**
     * 是否有空值
     */
    public static boolean hasEmpty(String value, String... values) {
        if (TextUtils.isEmpty(value)) {
            return true;
        } else {
            for (String str : values) {
                if (TextUtils.isEmpty(str)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 格式化金额
     */
    public static String moneyFormat(@Nullable Context context, double money) {
        return String.format(context.getString(R.string.moneySymbol) + "%.0f", money).replaceAll(",", ".");
    }

    public static String moneyConversion(double paidAmount) {
        return String.format("%.0f", paidAmount).replace(",", ".");
    }

    /**
     * 格式化时间
     */
    @Nullable
    public static String periodFormat(@Nullable Context context, double term, @NonNull String periodUnit) {
        String result = "" + (int) term + periodUnitFormat(context, periodUnit);
        return result;
    }

    public static String periodUnitFormat(Context context, String periodUnit) {
        String unit = context.getResources().getString(R.string.days);
        if ("D".equals(periodUnit)) {
            unit = context.getString(R.string.days);
        } else if ("M".equals(periodUnit)) {
            unit = context.getString(R.string.months);
        } else if ("Y".equals(periodUnit)) {
            unit = context.getString(R.string.years);
        }
        return unit;
    }

    public static String dayTimeFormat(Context context, int period) {
        StringBuffer result = new StringBuffer();
        int days = period;
        if (days > 365) {
            int year = days / 365;
            result.append(year + context.getString(R.string.years));
            days = days % 365;
        }

        if (days > 30) {
            int month = days / 30;
            result.append(month + context.getString(R.string.months));
            days = days & 30;
        }

        result.append(days + context.getString(R.string.days));
        return result.toString();
    }


    /**
     * 序列化对象
     */
    public static String fromBean(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = null;
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            return base64(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 反序列化对象
     */
    public static Object toBean(String str) {
        try {
            byte[] bytes = Base64.decode(str, Base64.NO_WRAP);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * String转base64
     */
    public static String base64(String content) {
        if (!TextUtils.isEmpty(content))
            return Base64.encodeToString(content.getBytes(), Base64.DEFAULT);
        else
            return "";
    }

    /**
     * String转base64
     */
    public static String base64(byte[] bytes, int flag) {
        if (bytes != null && bytes.length > 0)
            return Base64.encodeToString(bytes, flag);
        else
            return "";
    }


    /**
     * MD5
     */
    public static String MD5(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 格式化时间
     */
    public static String convertTime(String srcTime, String formatStyle) {
        String format = srcTime.contains("T") ? "yyyy-MM-dd'T'HH:mm:ss'Z'" : "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT00:00"));
        SimpleDateFormat simpleDateFormatLocal = new SimpleDateFormat(formatStyle);
        simpleDateFormatLocal.setTimeZone(TimeZone.getDefault());
        try {
            if (TextUtils.isEmpty(srcTime)) {
                return "0";
            }
            Date srcDate = simpleDateFormat.parse(srcTime);
            String targetTime = simpleDateFormatLocal.format(srcDate);
            return targetTime;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "0";
    }


    /**
     * 转换时间(String -> Date)
     */
    public static Date stringToDate(String time, String format) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(format);
            Date date = formatter.parse(time);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换时间(Date -> String)
     */
    public static String dateToString(Date date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String time = formatter.format(date);
        return time;
    }


    public static int dpToPx(Context context, float dp) {
        return (int) (context.getApplicationContext().getResources().getDisplayMetrics().densityDpi / 160 * dp);
    }


}
