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

import com.red.circle.component.core.i18n.I18nMessageUtils;
import com.red.circle.framework.core.dto.CommonCommand;
import com.red.circle.framework.web.constant.SystemDefaultConstant;
import com.red.circle.framework.web.i18n.I18nProperties;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.other.app.convertor.user.UserExpandAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.user.UserExpandProfileCO;
import com.red.circle.other.infra.database.rds.service.user.user.ExpandService;
import java.util.Objects;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author pengliang on 2020/11/6
 */
@Component
@AllArgsConstructor
public class UserExpandGetOrCreateQryExe {

  private final ExpandService expandService;
  private final I18nProperties i18nProperties;
  private final UserExpandAppConvertor userExpandAppConvertor;

  public UserExpandProfileCO execute(CommonCommand cmd) {
    UserExpandProfileCO expandCO = userExpandAppConvertor.toUserExpandCO(
        expandService.getById(cmd.requiredReqUserId()));
    if (Objects.isNull(expandCO)) {
      String lang = i18nProperties.containsAllowLocale(cmd.getReqLanguage())
          ? cmd.getReqLanguage()
          : SystemDefaultConstant.DEFAULT_LANG_STR;
      expandService.init(cmd.requiredReqUserId(), lang);
      UserExpandProfileCO expand = new UserExpandProfileCO();
      expand.setUserId(cmd.requiredReqUserId());
      expand.setLanguage(lang);
      expand.setLastActiveTime(TimestampUtils.now());
      expand.setPurchasing(Boolean.FALSE);
      expand.setSignature(I18nMessageUtils.get("USER_PROFILE_DESC.body"));
      return expand;
    }

    expandCO.setSignature(
        StringUtils.isBlankOrElseGet(expandCO.getSignature(),
            () -> I18nMessageUtils.get("USER_PROFILE_DESC.body"))
    );
    return expandCO;
  }

}
