package com.red.circle.other.app.command.sys.query;

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.convertor.sys.SysAppVersionManageAppConvertor;
import com.red.circle.other.app.dto.clientobject.sys.VersionManageCO;
import com.red.circle.other.infra.database.rds.entity.sys.VersionManage;
import com.red.circle.other.infra.database.rds.service.sys.VersionManageService;
import com.red.circle.other.infra.database.rds.service.sys.VersionUpdateDescriptionService;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 获取最新版本信息
 *
 * @author pengliang on 2020/11/14
 */
@Component
@RequiredArgsConstructor
public class LatestVersionManageGetQryExe {

  private final VersionManageService versionManageService;
  private final SysAppVersionManageAppConvertor sysAppVersionManageAppConvertor;
  private final VersionUpdateDescriptionService versionUpdateDescriptionService;

  public VersionManageCO execute(AppExtCommand cmd) {

    VersionManageCO versionCO = sysAppVersionManageAppConvertor.toVersionManageCO(getVersion(cmd));
    if (Objects.nonNull(versionCO)) {
      versionCO.setUpdateDescribe(getUpdateDescription(cmd, versionCO));
      versionCO.setUpdateWorshipDescribe(getUpdateWorshipDescription(cmd, versionCO));
    }
    return versionCO;
  }

  private String getUpdateWorshipDescription(AppExtCommand cmd, VersionManageCO versionCO) {
    return Optional.ofNullable(versionUpdateDescriptionService
            .getUpdateWorshipDescription(versionCO.getId(), cmd.getReqLanguage()))
        .orElse(null);
  }

  private String getUpdateDescription(AppExtCommand cmd, VersionManageCO versionCO) {
    return Optional.ofNullable(versionUpdateDescriptionService
            .getUpdateDescription(versionCO.getId(), cmd.getReqLanguage()))
        .orElse(versionCO.getUpdateDescribe());
  }

  private VersionManage getVersion(AppExtCommand cmd) {
    return versionManageService
        .getVersion(cmd.requireReqSysOrigin()
            , cmd.getReqClient().getClientName()
            , cmd.getReqAppIntel().getChannel()
            , Boolean.FALSE);
  }
}
