package mobvista.dmp.datasource.adn.mapreduce;

import mobvista.dmp.util.MRUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

/**
 * @package: mobvista.dmp.datasource.adn.mapreduce
 * @author: wangjf
 * @date: 2019-07-04
 * @time: 14:37
 * @emial: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class GetDevIdUtil {
    private static Pattern idPtn = Pattern.compile("0*-0*-0*-0*-0*");
    private static Pattern didPtn = Pattern.compile("^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$");
    private static Pattern splitPtn = Pattern.compile("-");

    public static String getIdByIdAndPlatform(String gaid, String idfa, String extSysid, String platform) {

        String devId = "";
        String deviceType = "";
        if (!idPtn.matcher(gaid).matches() && splitPtn.split(gaid).length == 5 && "android".equals(platform.toLowerCase())) {
            devId = gaid;
            deviceType = "gaid";
        } else if (!idPtn.matcher(idfa).matches() && splitPtn.split(idfa).length == 5 && "ios".equals(platform.toLowerCase())) {
            devId = idfa;
            deviceType = "idfa";
        }
        if (StringUtils.isNotBlank(devId)) {
            return MRUtils.JOINER.join(devId, deviceType);
        } else {
            return null;
        }
    }

    public static String getExtSysId(String extSysid) {

        String devId = "";
        String deviceType = "sysid";
        if (StringUtils.isNotBlank(extSysid) && !",".equals(extSysid)) {
            String[] exts = extSysid.split(",");
            if (StringUtils.isNotBlank(exts[0]) && !idPtn.matcher(exts[0]).matches() && splitPtn.split(exts[0]).length == 5) {
                devId = exts[0];
            } else if (exts.length == 2 && !idPtn.matcher(exts[1]).matches() && splitPtn.split(exts[1]).length == 5) {
                devId = exts[1];
            }
        }
        if (StringUtils.isNotBlank(devId)) {
            return MRUtils.JOINER.join(devId, deviceType);
        } else {
            return null;
        }
    }

    public static String getIdfv(String cdn_ab) {

        String devId = "";
        if (StringUtils.isNotBlank(cdn_ab) && !",".equals(cdn_ab)) {
            String[] exts = cdn_ab.split(",", -1);
            if (StringUtils.isNotBlank(exts[0]) && didPtn.matcher(exts[0]).matches()) {
                devId = exts[0];
            }
        }
        if (StringUtils.isNotBlank(devId)) {
            return devId;
        } else {
            return "";
        }
    }
}
