package com.viettel.campaign.repository.ccms_full.impl;

import com.viettel.campaign.repository.ccms_full.ScenarioQuestionRepositoryCustom;
import com.viettel.campaign.utils.HibernateUtil;
import com.viettel.campaign.web.dto.ScenarioQuestionDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author anhvd_itsol
 */

@Repository
public class ScenarioQuestionRepositoryImpl implements ScenarioQuestionRepositoryCustom {
    private static final Logger logger = LogManager.getLogger(ScenarioQuestionRepositoryImpl.class);

    @Override
    public Integer countDuplicateQuestionCode(ScenarioQuestionDTO questionDTO) {
        logger.info("Start search duplicate quest code row::");
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Integer count = null;

        try {
            StringBuilder sb = new StringBuilder();
            //SELECT COUNT(1) FROM ScenarioQuestion WHERE code = :code AND scenarioId = :scenarioId AND campaignId = :campaignId AND companySiteId = :companySiteId AND status = 1"
            sb.append("SELECT COUNT(1) FROM SCENARIO_QUESTION WHERE 1 = 1 AND STATUS = 1 ");
            if (questionDTO.getScenarioQuestionId() != null) {
                sb.append(" AND SCENARIO_QUESTION_ID <> :p_question_id ");
            }
            if (questionDTO.getCode() != null) {
                sb.append(" AND CODE = :p_code ");
            }
            if (questionDTO.getCampaignId() != null) {
                sb.append(" AND CAMPAIGN_ID = :p_campaign_id");
            }
            if (questionDTO.getCompanySiteId() != null) {
                sb.append(" AND COMPANY_SITE_ID = :p_site_id");
            }
            SQLQuery query = session.createSQLQuery(sb.toString());
            if (questionDTO.getScenarioQuestionId() != null) {
                query.setParameter("p_question_id", questionDTO.getScenarioQuestionId());
            }
            if (questionDTO.getCode() != null) {
                query.setParameter("p_code", questionDTO.getCode());
            }
            if (questionDTO.getCampaignId() != null) {
                query.setParameter("p_campaign_id", questionDTO.getCampaignId());
            }
            if (questionDTO.getCompanySiteId() != null) {
                query.setParameter("p_site_id", questionDTO.getCompanySiteId());
            }

            final List<BigDecimal> obj = query.list();

            for (BigDecimal i : obj) {
                if (i != null) {
                    count = i.intValue();
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return count;
    }
}
