package com.viettel.campaign.service.impl;

import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.ccms_full.ContactQuestResult;
import com.viettel.campaign.model.ccms_full.Scenario;
import com.viettel.campaign.model.ccms_full.ScenarioAnswer;
import com.viettel.campaign.model.ccms_full.ScenarioQuestion;
import com.viettel.campaign.repository.ccms_full.*;
import com.viettel.campaign.service.ScenarioService;
import com.viettel.campaign.utils.Constants;
import com.viettel.campaign.web.dto.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author anhvd_itsol
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class ScenarioServiceImpl implements ScenarioService {
    private static final Logger logger = LogManager.getLogger(ScenarioServiceImpl.class);

    @Autowired
    ScenarioRepository scenarioRepository;

    @Autowired
    ScenarioQuestionRepository questionRepository;

    @Autowired
    ScenarioAnswerRepository answerRepository;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    ContactQuestResultRepository questResultRepository;

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public Scenario findScenarioByCampaignIdAndCompanySiteId(Long campaignId, Long companySiteId) {
        try {
            return scenarioRepository.findScenarioByCampaignIdAndCompanySiteId(campaignId, companySiteId);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO update(ScenarioDTO scenarioDTO) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            scenarioDTO.setUpdateBy(null);
            scenarioDTO.setUpdateTime(new Date());

            Scenario scenario = modelMapper.map(scenarioDTO, Scenario.class);
            scenarioRepository.save(scenario);
            resultDTO.setData(scenario);
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
            resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO sortQuestionAndAnswer(ScenarioDTO scenarioDTO) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<ScenarioQuestionDTO> lstQuestion = scenarioDTO.getLstQuestion();
            List<ScenarioAnswerDTO> lstAnswer = scenarioDTO.getLstAnswer();
            List<ScenarioQuestion> questionsToSort = new ArrayList<>();
            List<ScenarioAnswer> answersToSort = new ArrayList<>();
            if (lstQuestion.size() > 0) {
                lstQuestion.forEach(item -> {
                    ScenarioQuestion question = questionRepository.findScenarioQuestionByScenarioQuestionId(item.getScenarioQuestionId());
                    if (question != null) {
                        question.setOrderIndex(item.getOrderIndex());
                        questionsToSort.add(question);
                    }
                });
                questionRepository.saveAll(questionsToSort);
            }
            if (lstAnswer.size() > 0) {
                lstAnswer.forEach(item -> {
                    ScenarioAnswer answer = answerRepository.findScenarioAnswerByScenarioAnswerId(item.getScenarioAnswerId());
                    if (answer != null) {
                        answer.setOrderIndex(item.getOrderIndex());
                        answersToSort.add(answer);
                    }
                });
                answerRepository.saveAll(answersToSort);
            }

            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
            resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public Integer countDuplicateScenarioCode(Long companySiteId, String code, Long scenarioId) {
        try {
            return scenarioRepository.countDuplicateScenarioCode(companySiteId, code, scenarioId);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    public ResultDTO saveContacQuestResult(ContactQuestResultDTO dto) {
        ResultDTO resultDTO = new ResultDTO();

        if (dto != null) {
            ContactQuestResult cqr = questResultRepository.save(modelMapper.map(dto, ContactQuestResult.class));
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
            resultDTO.setData(cqr);
        } else {
            resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
            resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
        }

        return resultDTO;
    }
}
