package com.dxhy.portrait.business.entity.webservice;

import java.net.InetAddress;
import java.net.NetworkInterface;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.xstream.annotations.XStreamAlias;

import lombok.Getter;
import lombok.ToString;

/**
 * @author dxhy
 */
@Getter
@ToString
@XStreamAlias("HEADER")
public class RequestHead {

    @XStreamAlias("CLIENT_MAC")
    protected String clientMacModel;
    @XStreamAlias("CLIENT_IP")
    protected String clientIp;
    @XStreamAlias("CLIENT_PC")
    protected String clientPc;

    private RequestHead() {
        try {
            InetAddress ia = InetAddress.getLocalHost();
            this.clientPc = !StringUtils.isEmpty(ia.getHostName()) ? ia.getHostName() : "";
            this.clientIp = !StringUtils.isEmpty(ia.getHostAddress()) ? ia.getHostAddress() : "";
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
            String clientMac = "";
            // 下面代码是把mac地址拼装成String
            if (mac != null && mac.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    if (i != 0) {
                        sb.append("-");
                    }
                    // mac[i] & 0xFF 是为了把byte转化为正整数
                    String s = Integer.toHexString(mac[i] & 0xFF);
                    sb.append(s.length() == 1 ? 0 + s : s);
                }
                clientMac = sb.toString().toUpperCase();
            }
            // 把字符串所有小写字母改为大写成为正规的mac地址并返回
            this.clientMacModel = clientMac;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static volatile RequestHead requestHead = null;

    public static RequestHead getRequestHead() {
        if (requestHead == null) {
            synchronized (RequestHead.class) {
                if (requestHead == null) {
                    requestHead = new RequestHead();
                }
            }
        }
        return requestHead;
    }

}
