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.app.dto.clientobject.sys.VersionManageLatestAndReviewCO;
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 LatestAndReviewVersionManageGetQryExe {

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

  public VersionManageLatestAndReviewCO execute(AppExtCommand cmd) {

    VersionManage latest = getVersion(cmd, Boolean.FALSE);

    VersionManage review = getVersion(cmd, Boolean.TRUE);

    return new VersionManageLatestAndReviewCO()
        .setLatest(builderCO(cmd.getReqLanguage(),
            sysAppVersionManageAppConvertor.toVersionManageCO(latest)))
        .setReview(builderCO(cmd.getReqLanguage(),
            sysAppVersionManageAppConvertor.toVersionManageCO(review)));
  }

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


  private VersionManageCO builderCO(String language, VersionManageCO versionCO) {

    if (Objects.isNull(versionCO)) {
      return new VersionManageCO();
    }

    versionCO.setUpdateDescribe(Optional.ofNullable(versionUpdateDescriptionService
            .getUpdateDescription(versionCO.getId(), language))
        .orElse(versionCO.getUpdateDescribe()));
    return versionCO;
  }

}
