package com.handong.smartservice.service;

import com.handong.smartservice._AG;
import com.handong.smartservice.component.CtResponse;
import com.handong.smartservice.component.ErrorCode;
import com.handong.smartservice.mapper.VocMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class VocService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final VocMapper vocMapper;


    public VocService(VocMapper vocMapper) {
        this.vocMapper = vocMapper;
    }

    public CtResponse getVocDetail(String voc_id) {
        CtResponse result = new CtResponse();

        Map<String, Object> detail = vocMapper.selectDetailVoc(voc_id);

        if (voc_id == null || voc_id.isEmpty()) {
            result.setErrCode(ErrorCode.INVALID_PARAMETER);
            return result;
        }

        result.put("result", detail);
        return result;
    }

    public Map<String, Object> getVocList(Long offset, Long limit, String date_start, String date_end,
                String title, String content, String process) {
        Map<String, Object> mapResult = new HashMap<>();

        List<Map<String, Object>> listMap = (List<Map<String, Object>>)vocMapper.selectVoc(false, offset, limit, 
            date_start, date_end, title, content, process);
        mapResult.put("list", listMap);
        
        //Long totalCount = _AG.getTotalCount(vocMapper.selectVoc(true, offset, limit, 
        //    date_start, date_end, title, content, process));
        Long totalCount = _AG.getNumberFromQuery("COUNT(*)", vocMapper.selectVoc(true, offset, limit, 
            date_start, date_end, title, content, process));
        mapResult.put("totalCount", totalCount);
        mapResult.put("offset", offset);
        return mapResult;
    }

    public CtResponse addOrModifyVoc(boolean isModify, String voc_id, String title, String content) {
        CtResponse result = new CtResponse();

        if (isModify) {
            if (voc_id == null || voc_id.isEmpty()) {
                result.setErrCode(ErrorCode.INVALID_PARAMETER);
                return result;
            }

            vocMapper.updateVoc(_AG.toLong(voc_id), title, content);
        }
        else {
            vocMapper.insertVoc(title, content, 2L);
        }
        
        return result;
    }

    public CtResponse removeVoc(String ids) {
        CtResponse result = new CtResponse();

        List<Long> arrId = Arrays.stream(ids.split(","))
            .map(Long::parseLong)
            .collect(Collectors.toList());
        
        int changed = vocMapper.changeStateVoc(arrId, 2);
        //if (changed == 0) {
            //result.setErrCode(ErrorCode.QUERY_ERROR);
        //}
        
        return result;
    }
}
