package io.renren.common.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

import javax.imageio.ImageIO;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;

/**
 * My工具类
 *
 * @author huwhois huwhois@163.com
 */
public class MyUtils {

    public static String md5(String str) {
		return DigestUtils.md5DigestAsHex(str.getBytes());
    }

    /**
     * 将图片转换成base64格式进行存储
     * @param imagePath
     * @return
     */
    public static String encodeToString(String imagePath) throws IOException {
        String type = StringUtils.substring(imagePath, imagePath.lastIndexOf(".") + 1);
        BufferedImage image = ImageIO.read(new File(imagePath));
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            Base64.Encoder encoder = Base64.getEncoder();

            imageString = encoder.encodeToString(imageBytes);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

    /**
     * 判断手机号phone是否正确格式
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone){
        Pattern pattern = Pattern.compile("^(1[3-9]\\d{9}$)");
        Matcher matcher = pattern.matcher(phone);
        
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    /**
     * 判断邮件email是否正确格式
     */
    public boolean checkEmail(String email){
        Pattern pattern = Pattern.compile("^/w+([-.]/w+)*@/w+([-]/w+)*/.(/w+([-]/w+)*/.)*[a-z]{2,3}$");
        Matcher matcher = pattern.matcher(email);
        
        if (matcher.matches()) {
            return true;
        }
        return false;
    }
}
