package com.viettel.campaign.repository;

import com.viettel.campaign.web.dto.CampaignDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

public class CampaignRepositoryImpl implements CampaignRepositoryCustom {

    @Autowired
    EntityManager entityManager;

    @Override
    public List<CampaignDTO> searchCampaignExecute(String agentId, Pageable pageable) {
        List<CampaignDTO> lst = new ArrayList<>();
        String expression = new StringBuilder()
                .append(" SELECT C.CAMPAIGN_ID, C.CAMPAIGN_NAME, C.STATUS ")
                .append(" FROM CAMPAIGN C ")
                .append(" INNER JOIN CAMPAIGN_AGENT CA ON C.CAMPAIGN_ID = CA.CAMPAIGN_ID ")
                .append(" WHERE 1 = 1 ")
                .append(" AND CA.AGENT_ID = :pAgentId ")
                .append(" AND C.STATUS IN (2,3) ")
                .toString();

        Query query = entityManager.createNativeQuery(expression);
        query.setParameter("pAgentId", agentId);

        List<Object[]> data = query.getResultList();

        for (Object[] obj : data) {
            CampaignDTO item = new CampaignDTO();
            item.setCampaignId((Long)obj[0]);
            item.setCampaignName((String)obj[1]);
            item.setStatus((Short) obj[0]);

            lst.add(item);
        }

        return lst;
    }
}
