package com.yeejoin.amos.boot.module.common.biz.refresh.dispatch;

import com.yeejoin.amos.boot.module.common.api.entity.TzsDataRefreshMessage;
import com.yeejoin.amos.boot.module.common.api.service.IDataRefreshDispatch;
import com.yeejoin.amos.boot.module.common.biz.constats.Constants;
import com.yeejoin.amos.boot.module.common.biz.refresh.factory.RefreshHandlerFactory;
import com.yeejoin.amos.boot.module.common.biz.service.impl.TzsDataRefreshMessageServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RequiredArgsConstructor
public class RefreshDispatch implements IDataRefreshDispatch {

    private final RefreshHandlerFactory handlerFactory;
    private final TzsDataRefreshMessageServiceImpl tzsDataRefreshMessageService;

    @Override
    @Async
    public void doDispatch(TzsDataRefreshMessage message) {
        handlerFactory.getRefreshHandler(message.getDataType()).doRefresh(message);
        finishMessage(message);
    }

    private void finishMessage(TzsDataRefreshMessage message) {
        message.setStatus(Constants.REFRESH_STATUS_SUCCESS);
        message.setRecDate(new Date());
        tzsDataRefreshMessageService.saveOrUpdate(message);
    }
}
