package com.red.circle.other.infra.gateway.user;

import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.tool.core.thread.ThreadPoolManager;
import com.red.circle.other.domain.gateway.user.ability.RegisterDeviceGateway;
import com.red.circle.other.infra.database.rds.service.user.device.DeviceRegisterQuantityService;
import com.red.circle.other.infra.database.rds.service.user.device.IpRegisterQuantityService;
import com.red.circle.other.inner.model.cmd.user.IncrDeviceRegisterCmd;
import com.red.circle.other.inner.model.cmd.user.device.AllowDeviceRegisterCmd;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 注册设备 实现.
 *
 * @author pengliang on 2023/12/17
 */
@Component
@RequiredArgsConstructor
public class RegisterDeviceGatewayImpl implements RegisterDeviceGateway {

  private final IpRegisterQuantityService ipRegisterQuantityService;
  private final DeviceRegisterQuantityService deviceRegisterQuantityService;

  /**
   * 累计注册数量.
   */
  @Override
  public void incrRegisterQuantityAsync(IncrDeviceRegisterCmd cmd) {
    ThreadPoolManager.getInstance().execute(() -> {
      if (StringUtils.isNotBlank(cmd.getDeviceNo())) {
        deviceRegisterQuantityService.incrQuantity(cmd.getDeviceNo(), cmd.getSysOrigin());
      }

      if (StringUtils.isNotBlank(cmd.getIp())) {
        ipRegisterQuantityService.incrQuantity(cmd.getIp(), cmd.getSysOrigin());
      }
    });
  }

  /**
   * 是否允许用户设备注册.
   *
   * @return true 允许注册、false 不允许
   */
  @Override
  public boolean checkAllowDeviceRegister(AllowDeviceRegisterCmd cmd) {
    return !isLimitDevice(cmd) && !isLimitIp(cmd);
  }

  private boolean isLimitIp(AllowDeviceRegisterCmd cmd) {
    return cmd.checkIp() && checkIpQuantity(cmd);
  }

  private boolean isLimitDevice(AllowDeviceRegisterCmd cmd) {
    return cmd.checkDevice() && checkDeviceNoQuantity(cmd);
  }

  private boolean checkIpQuantity(AllowDeviceRegisterCmd cmd) {
    return ipRegisterQuantityService.getIpQuantity(cmd.getIp(), cmd.getSysOrigin())
        >= cmd.getIpLimit();
  }

  private boolean checkDeviceNoQuantity(AllowDeviceRegisterCmd cmd) {
    return deviceRegisterQuantityService.getDeviceNoQuantity(cmd.getDeviceNo(), cmd.getSysOrigin())
        >= cmd.getDeviceLimit();
  }

}
