package com.izouma.nineth.task;

import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AssetRepo;
import com.izouma.nineth.service.AssetMintService;
import com.izouma.nineth.service.AssetService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 资产铸造任务
 */
@Service
@AllArgsConstructor
@Slf4j
public class AssetMintServiceTask {

    private AssetRepo assetRepo;

    private AssetMintService assetMintService;

    /**
     * 自动铸造失败的资产
     */
    @Scheduled(fixedDelay = 1000 * 60 * 20)
    public void batchMint(){
        List<Long> assetIdList = assetRepo.findWaitMintAssetList();
        if(assetIdList.size() > 0){
            log.info("开始自动铸造资产，数量：" + assetIdList.size());
        }

        AtomicInteger successCount  = new AtomicInteger(0);
        assetIdList.forEach(assetId -> {
            try {
                assetMintService.mint(assetId);
                successCount.addAndGet(1);
            } catch(BusinessException e){
                log.error("铸造失败，assetId:" + assetId + ", error:" +  e.getMessage());
            }catch (Exception e) {
                log.error("铸造失败，assetId:" + assetId, e);
            }
        });
        if(successCount.get() > 0){
            log.info("成功铸造资产，数量：" + successCount.get());
        }
    }

}
