package com.red.circle.other.app.command.user;

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.common.business.enums.PushPlatformEnum;
import com.red.circle.framework.core.dto.ReqAppIntel;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.other.app.dto.cmd.user.user.UploadDeviceCmd;
import com.red.circle.other.infra.database.rds.entity.user.device.PushDevice;
import com.red.circle.other.infra.database.rds.entity.user.user.LatestMobileDevice;
import com.red.circle.other.infra.database.rds.service.user.device.LatestMobileDeviceService;
import com.red.circle.other.infra.database.rds.service.user.device.PushDeviceService;
import com.red.circle.other.infra.database.rds.service.user.user.RecentlyActiveService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 上传最新设备信息.
 *
 * @author pengliang on 2020/11/4
 */
@Component
@RequiredArgsConstructor
public class UploadLatestDeviceCmdExe {

  private static final Logger log = LoggerFactory.getLogger(UploadLatestDeviceCmdExe.class);
  private final PushDeviceService pushDeviceService;
  private final RecentlyActiveService recentlyActiveService;
  private final LatestMobileDeviceService latestMobileDeviceService;

  public void execute(UploadDeviceCmd cmd) {
    LatestMobileDevice latestMobileDevice = toLatestMobileDevice(cmd);
    latestMobileDevice.setUserId(cmd.getReqUserId());
    latestMobileDeviceService.saveLatestMobileDevice(latestMobileDevice);
    recentlyActiveService.add(cmd.requireReqSysOrigin(), cmd.getReqUserId());

    if (StringUtils.isNotBlank(cmd.getPushDeviceNo())) {
      pushDeviceService.saveUnique(new PushDevice()
          .setSysOrigin(cmd.requireReqSysOrigin())
          .setUserId(cmd.requiredReqUserId())
          .setDeviceNo(cmd.getPushDeviceNo())
          .setPushPlatform(
              cmd.checkAndroid() ? PushPlatformEnum.UMENG.name() : PushPlatformEnum.GOOGLE.name())
          .setPlatform(cmd.getReqClient().name())
      );
    }

  }

  private LatestMobileDevice toLatestMobileDevice(AppExtCommand cmd) {
    ReqAppIntel reqAppIntel = cmd.getReqAppIntel();

    return new LatestMobileDevice()
        .setUserId(cmd.getReqUserId())
        .setLanguage(cmd.getReqLanguage())
        .setZoneId(cmd.getReqZoneId())
        .setIp(cmd.getReqIp())
        .setImei(cmd.getReqImei())
        .setRequestClient(cmd.getReqClient().name())
        .setPhoneModel(reqAppIntel.getModel())
        .setPhoneSysVersion(reqAppIntel.getSysVersion())
        .setBuildVersion(reqAppIntel.getBuild())
        .setAppVersion(reqAppIntel.getVersion())
        .setSysOrigin(cmd.requireReqSysOrigin());
  }

}
