package com.viettel.campaign.service;

import com.viettel.campaign.web.dto.ApParamDTO;
import com.viettel.campaign.web.dto.ResultDTO;
import com.viettel.campaign.mapper.ApParamMapper;
import com.viettel.campaign.model.ApParam;
import com.viettel.campaign.repository.ApParamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

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

@Service
public class ApParamServiceImpl implements ApParamService {

    @Autowired
    ApParamRepository apParamRepository;

    @Override
    public Iterable<ApParam> getAllParams(int page, int pageSize, String sort) {
        return apParamRepository.findAll(PageRequest.of(page, pageSize, Sort.by(sort)));
    }

    @Override
    public List<ApParam> getParamByName(int page, int pageSize, String sort, String parName) {
        List<ApParam> lst = new ArrayList<>();

        lst = apParamRepository.findParamByName(parName, PageRequest.of(page, pageSize, Sort.by(sort)));

        return lst;
    }

    @Override
    public ResultDTO createApParam(ApParamDTO apParamDTO) {
        ResultDTO result = new ResultDTO();
        ApParamMapper apParamMapper = new ApParamMapper();
        ApParam apparam = new ApParam();

        try {
            if (apParamDTO != null) {
                apparam = apParamRepository.save(apParamMapper.toPersistenceBean(apParamDTO));

                result.setErrorCode("0");
                result.setDescription("create apparam");
                result.setData(apparam);
            } else {
                result.setErrorCode("-1");
                result.setDescription("create apparam FAIL");
                result.setData(apparam);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
