package kr.co.jinwoosi.clfd.clfd.prod.service;

import kr.co.jinwoosi.clfd.clfd.prod.model.ProdLike;
import kr.co.jinwoosi.clfd.conts.prod.mapper.ProdMapper;
import kr.co.jinwoosi.clfd.conts.prod.model.Prod;
import kr.co.jinwoosi.clfd.conts.prod.model.ProdSearch;
import kr.co.jinwoosi.clfd.framework.cd.model.CdDtl;
import kr.co.jinwoosi.clfd.framework.cd.service.CdDtlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ClfdProdService {

    @Autowired
    private ProdMapper prodMapper;
    @Autowired
    private CdDtlService cdDtlService;
    @Autowired
    private ProdLikeService prodLikeService;

    public List<Prod> selectList(ProdSearch prodSearch) {
        return prodMapper.selectList(prodSearch);
    }

    public List<Prod> selectListWithLike(ProdSearch prodSearch, Long userId) {
        List<Prod> prodList = this.selectList(prodSearch);
        prodList.forEach(prod -> {
            ProdLike prodLike = prodLikeService.select(prod.getProdId(), userId);
            prod.setLike(prodLike != null);
        });
        return prodList;
    }

    public Prod select(ProdSearch prodSearch) {
        return prodMapper.select(prodSearch);
    }

    public Prod selectWithLike(ProdSearch prodSearch, Long userId) {
        Prod prod = prodMapper.select(prodSearch);
        if (prod!=null) {
            ProdLike prodLike = prodLikeService.select(prod.getProdId(), userId);
            prod.setLike(prodLike != null);
        }
        return prod;
    }

    public void update(Prod prod) {
        prodMapper.update(prod);
    }

    public List<CdDtl> getProdTyCdDtlList() {
        CdDtl cdDtl = new CdDtl();
        cdDtl.setCdId("prodTy");
        return cdDtlService.selectList(cdDtl);
    }

    public void plusRcmdNo(Prod prod) {
        Long rcmdNo = prod.getRcmdNo();
        if (rcmdNo==null || rcmdNo < 0) {
            rcmdNo = 0L;
        }
        prod.setRcmdNo(++rcmdNo);
    }

    public void minusRcmdNo(Prod prod) {
        Long rcmdNo = prod.getRcmdNo();
        if (rcmdNo==null || rcmdNo-1 < 0) {
            return;
        }
        prod.setRcmdNo(--rcmdNo);
    }
}
