package com.docus.server.common.process;

import com.docus.core.util.json.JSON;
import com.docus.log.context.TrackContext;
import com.docus.log.processor.AbstractProcessor;
import com.docus.server.common.MsgConstants;
import com.docus.server.dto.scheduling.management.schcollector.UpdateSchCollectorDTO;
import com.docus.server.dto.scheduling.management.schterminator.CommMsgDTO;
import com.docus.server.entity.scheduling.management.SchCollectorVersionFile;
import com.docus.server.service.ICommMsgService;
import com.docus.server.service.ISchCollectorVersionFileService;
import com.docus.server.service.ISchCollectorVersionService;
import com.docus.server.vo.scheduling.management.schcollectorversion.SchCollectorVersionVO;
import com.docus.server.vo.scheduling.management.schcollectorversion.TcpSchCollectorVersionContentVO;
import com.google.common.collect.Lists;

import javax.annotation.Resource;
import java.util.List;

/**
 * tcp 管理
 */
public class TcpProcessor extends AbstractProcessor {
    @Resource
    private ICommMsgService iCommMsgService;
    @Resource
    private ISchCollectorVersionFileService iSchCollectorVersionFileService;
    @Resource
    private ISchCollectorVersionService iSchCollectorVersionService;

    @Override
    protected Object doProcess(TrackContext context) {
        return logProcess(context);
    }

    private boolean logProcess(TrackContext context) {
        boolean error = context.isError();
        if (!error) {
            UpdateSchCollectorDTO updateSchCollectorDTO = (UpdateSchCollectorDTO) context.getArgs()[0];
            Long collectorId = updateSchCollectorDTO.getCollectorId();
            Long collectorVersionId = updateSchCollectorDTO.getCollectorVersionId();

            SchCollectorVersionFile schCollectorVersionFile = iSchCollectorVersionFileService.findByCollectorIdAndVersionId(collectorId, collectorVersionId);
            SchCollectorVersionVO schCollectorVersionVO = iSchCollectorVersionService.findById(String.valueOf(collectorVersionId));

            TcpSchCollectorVersionContentVO tcpSchCollectorVersionContentVO = new TcpSchCollectorVersionContentVO();
            tcpSchCollectorVersionContentVO.setCollectorId(collectorId);
            tcpSchCollectorVersionContentVO.setFilePath(schCollectorVersionFile.getFilePath());
            tcpSchCollectorVersionContentVO.setCollectorVersion(schCollectorVersionVO.getCollectVersion());

            List<TcpSchCollectorVersionContentVO> tcpSchCollectorVersionContentVOList = Lists.newArrayList(tcpSchCollectorVersionContentVO);

            CommMsgDTO commMsgDTO = CommMsgDTO.builder()
                .content(JSON.toJSON(tcpSchCollectorVersionContentVOList))
                .messageType(MsgConstants.UPDATE_COLLECTOR_FILE)
                .build();

            iCommMsgService.clientsCommand(commMsgDTO);
        }
        return error;
    }
}
