package com.viettel.campaign.service.impl;

import com.viettel.campaign.config.DataSourceQualify;
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.ScenarioAnswerRepository;
import com.viettel.campaign.repository.ccms_full.ScenarioQuestionRepository;
import com.viettel.campaign.repository.ccms_full.ScenarioRepository;
import com.viettel.campaign.service.ScenarioService;
import com.viettel.campaign.utils.Constants;
import com.viettel.campaign.web.dto.ResultDTO;
import com.viettel.campaign.web.dto.ScenarioAnswerDTO;
import com.viettel.campaign.web.dto.ScenarioDTO;
import com.viettel.campaign.web.dto.ScenarioQuestionDTO;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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;

    @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
    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;
    }
}
