package com.ruoyi.web.modules.video.support;

import java.util.regex.Pattern;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.video.domain.BizLivestockMonitor;

/**
 * 畜牧监控入参校验。
 */
public final class LivestockMonitorValidation
{
    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$");

    private LivestockMonitorValidation()
    {
    }

    public static void trimFieldsForSave(BizLivestockMonitor row)
    {
        if (row == null)
        {
            return;
        }
        if (row.getMonitorName() != null)
        {
            row.setMonitorName(row.getMonitorName().trim());
        }
        if (row.getInstallLocation() != null)
        {
            row.setInstallLocation(row.getInstallLocation().trim());
        }
        if (row.getIpAddress() != null)
        {
            row.setIpAddress(row.getIpAddress().trim());
        }
    }

    public static void validateMonitorName(String monitorName)
    {
        if (StringUtils.isEmpty(monitorName) || monitorName.length() < 1 || monitorName.length() > 10)
        {
            throw new ServiceException("监控名称须为1～10个字符");
        }
    }

    public static void validateInstallLocation(String installLocation)
    {
        if (StringUtils.isEmpty(installLocation) || installLocation.length() < 1 || installLocation.length() > 10)
        {
            throw new ServiceException("安装位置须为1～10个字符");
        }
    }

    public static void validateIpAddress(String ipAddress)
    {
        if (StringUtils.isEmpty(ipAddress))
        {
            throw new ServiceException("请输入正确的 IP 地址");
        }
        if (ipAddress.length() > 20)
        {
            throw new ServiceException("IP 地址不能超过 20 个字符");
        }
        if (!IPV4_PATTERN.matcher(ipAddress).matches())
        {
            throw new ServiceException("请输入正确的 IP 地址");
        }
    }

    public static void validateOwnerType(Integer ownerType)
    {
        if (!LivestockMonitorRules.isOwnerTypeValid(ownerType))
        {
            throw new ServiceException("所属主体类型无效");
        }
    }

    public static void validateOwnerId(Long ownerId)
    {
        if (ownerId == null)
        {
            throw new ServiceException("请选择所属主体");
        }
    }

    public static void validateRowForSave(BizLivestockMonitor row)
    {
        trimFieldsForSave(row);
        validateMonitorName(row.getMonitorName());
        validateOwnerType(row.getOwnerType());
        validateOwnerId(row.getOwnerId());
        validateInstallLocation(row.getInstallLocation());
        validateIpAddress(row.getIpAddress());
    }
}
