package com.bsmlab.dfx.dfxconsole.app.agent.service;

import com.bsmlab.dfx.dfxconsole.framework.dto.SearchParameterDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class DfxAgentMessageHistoryService {
    private final DfxAgentMessageHistoryMapper dfxAgentMessageHistoryMapper;

    public List<DfxAgentMessageDto> selectDfxAgentMessageDtoList(SearchParameterDto searchParameterDto) {
        List<DfxAgentMessageDto> dfxAgentMessageDtoList = dfxAgentMessageHistoryMapper.selectDfxAgentMessageList(searchParameterDto);
        return dfxAgentMessageDtoList;
    }

    public int selectDfxAgentMessageDtoListTotalCount() {
        int totalCount = dfxAgentMessageHistoryMapper.selectDfxAgentMessageListTotalCount();
        return totalCount;
    }

    public List<Map<String, Object>> selectDfxAgentMessageData(DfxAgentMessageDto inputDfxAgentMessageDto) throws JsonProcessingException {
        DfxAgentMessageDto dfxAgentMessageDto = dfxAgentMessageHistoryMapper.selectDfxAgentMessageBySenderAgentIdAndMessageUuid(inputDfxAgentMessageDto);
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> dataMapList = objectMapper.readValue(dfxAgentMessageDto.getMessageData(), new TypeReference<List<Map<String, Object>>>() {});
        return dataMapList;
    }

    public List<DfxAgentMessageHistoryDto> selectDfxAgentMessageHistoryDtoList() {
        List<DfxAgentMessageHistoryDto> dfxAgentMessageHistoryDtoList = dfxAgentMessageHistoryMapper.selectDfxAgentMessageHistoryList();
        return dfxAgentMessageHistoryDtoList;
    }

    @Transactional
    @Scheduled(cron = "1 0/10 * * * *")
    public void autoSaveDfxAgentMessageByDfxAgentMessageHistory() {
        this.dfxAgentMessageHistoryMapper.mergeDfxAgentMessageByDfxAgentMessageHistory();
    }
}
