/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.security.common.utils;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通用工具类
 *
 * @author Chill
 */
@Slf4j
public class CommonUtil {
	public static String getIpAddress() {
		Enumeration en;
		try {
			en = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException var8) {
			log.error(var8.getMessage());
			return "127.0.0.1";
		}

		ArrayList tmpMacList = new ArrayList();

		while(en.hasMoreElements()) {
			NetworkInterface iface = (NetworkInterface)en.nextElement();
			List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
			Iterator var4 = addrs.iterator();

			while(var4.hasNext()) {
				InterfaceAddress addr = (InterfaceAddress)var4.next();
				InetAddress ip = addr.getAddress();
				if (ip != null) {
					String newIP = ip.toString().replace("/", "");
					if (!newIP.contains("127")) {
						tmpMacList.add(newIP);
					}
				}
			}
		}

		if (tmpMacList.size() <= 0) {
			return "127.0.0.1";
		} else {
			List<String> unique = (List)tmpMacList.stream().distinct().collect(Collectors.toList());
			return (String)unique.get(0);
		}
	}

	public static String getMacAddress() {
		ArrayList tmpMacList = new ArrayList();

		try {
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
			StringBuilder sb = new StringBuilder();

			label53:
			while(en.hasMoreElements()) {
				NetworkInterface iface = (NetworkInterface)en.nextElement();
				List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
				Iterator var5 = addrs.iterator();

				while(true) {
					byte[] mac;
					do {
						NetworkInterface network;
						do {
							if (!var5.hasNext()) {
								continue label53;
							}

							InterfaceAddress addr = (InterfaceAddress)var5.next();
							InetAddress ip = addr.getAddress();
							network = NetworkInterface.getByInetAddress(ip);
						} while(network == null);

						mac = network.getHardwareAddress();
					} while(mac == null);

					sb.delete(0, sb.length());

					for(int i = 0; i < mac.length; ++i) {
						sb.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? "-" : ""));
					}

					tmpMacList.add(sb.toString());
				}
			}
		} catch (Exception var11) {
			log.error(var11.getMessage());
			return "00-50-56-9C-0D-0A";
		}

		if (tmpMacList.size() <= 0) {
			return "00-50-56-9C-0D-0A";
		} else {
			List<String> unique = (List)tmpMacList.stream().distinct().collect(Collectors.toList());
			return (String)unique.get(0);
		}
	}

	public static String compressBase64Image(String formatName, String base64, int maxLength, Double quality, Double step) throws IOException {
		if (base64.length() > maxLength) {
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bytes = decoder.decodeBuffer(base64);
			ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
			BufferedImage src = ImageIO.read(stream);
			int width = src.getWidth();
			int height = src.getHeight();
			BufferedImage output = Thumbnails.of(src).size(src.getWidth(), src.getHeight()).asBufferedImage();
			String result = imageToBase64(formatName, output);
			quality = null == quality ? 0.95 : quality;
			output = Thumbnails.of(output).scale(quality).asBufferedImage();
			step = null == step ? 0.05 : step;
			base64 = imageToBase64(formatName, output);
			if (base64.length() > maxLength) {
				base64 = compressBase64Image(formatName, base64, maxLength, quality - step, step);
			}
		}
		return base64;
	}

	private static String imageToBase64(String formatName, BufferedImage bufferedImage) throws IOException {
		Base64 encoder = new Base64();
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, formatName, byteArrayOutputStream);
		return new String(encoder.encode(byteArrayOutputStream.toByteArray()));
	}

	public static String multipartFileToBase64(MultipartFile file) {
		String base64 = "";
		if (null != file) {
			BASE64Encoder encoder = new BASE64Encoder();
			try {
				base64 = encoder.encode(file.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
				return "";
			}
		}
		return base64.replaceAll("\r\n", "");
	}


}
