package com.red.circle.other.app.service.pet;

import com.red.circle.common.business.dto.PageQueryCmd;
import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.convertor.MybatisConvertor;
import com.red.circle.other.app.command.pet.PetActivationCmdExe;
import com.red.circle.other.app.command.pet.PetLibraryDetailsQueryExe;
import com.red.circle.other.app.command.pet.query.PetListLibraryPageExe;
import com.red.circle.other.app.dto.clientobject.pet.PetLibraryCO;
import com.red.circle.other.app.dto.clientobject.pet.PetLibraryDetailsCO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 宠物库 实现.
 *
 * @author pengliang on 2021/10/14
 */
@Service
@RequiredArgsConstructor
public class PetLibraryServiceImpl implements PetLibraryService {

  private final RedisService redisService;
  private final PetActivationCmdExe petActivationCmdExe;
  private final PetListLibraryPageExe petListLibraryPageExe;
  private final PetLibraryDetailsQueryExe petLibraryDetailsQueryExe;

  @Override
  public PageResult<PetLibraryCO> pageLibrary(PageQueryCmd cmd) {
    return MybatisConvertor.toPageResult(petListLibraryPageExe.execute(cmd));
  }

  @Override
  public PetLibraryDetailsCO getLibraryDetails(AppIdLongCmd cmd) {
    return petLibraryDetailsQueryExe.execute(cmd);
  }

  @Override
  public void activation(AppIdLongCmd cmd) {
    // 上锁
    String key = "activation:" + cmd.getId();
    try {
      ResponseAssert.isTrue(CommonErrorCode.REQUEST_LIMITING, redisService.lock(key, 60));
      petActivationCmdExe.execute(cmd);
    } finally {
      redisService.unlock(key);
    }
  }

}
