package com.eactive.eai.rms.onl.apim.portalfaq;

import com.eactive.apim.portal.portalfaq.entity.PortalFaq;
import com.eactive.apim.portal.user.entity.UserInfo;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.man.user.UserInfoService;
import com.eactive.eai.rms.data.entity.onl.apim.portalfaq.PortalFaqSearch;
import com.eactive.eai.rms.data.entity.onl.apim.portalfaq.PortalFaqService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalFaqManService extends BaseService {
	private final PortalFaqService portalFaqService;
	private final PortalFaqUIMapper portalFaqUIMapper;
	private final UserInfoService userInfoService;

	@Autowired
	public PortalFaqManService(PortalFaqService portalFaqService,
							   PortalFaqUIMapper portalFaqUIMapper,
							   UserInfoService userInfoService){
		this.portalFaqService = portalFaqService;
		this.portalFaqUIMapper = portalFaqUIMapper;
		this.userInfoService = userInfoService;
	}

	public Page<PortalFaqUI> selectList(Pageable pageable, PortalFaqSearch portalFaqSearch) {
		Page<PortalFaq> portalFaqPage = portalFaqService.findAll(pageable, portalFaqSearch);
		return portalFaqPage.map(portalFaq -> {
			PortalFaqUI portalFaqUI = portalFaqUIMapper.toVo(portalFaq);
			portalFaqUI.setCreatedByName(getCreatedByName(portalFaq.getCreatedBy()));
			return portalFaqUI;
		});
	}

	public PortalFaqUI selectDetail(String id) {
		PortalFaq portalFaq = portalFaqService.getById(id);
		PortalFaqUI portalFaqUI =  portalFaqUIMapper.toVo(portalFaq);
		portalFaqUI.setCreatedByName(getCreatedByName(portalFaq.getCreatedBy()));
		return portalFaqUI;
	}

	private String getCreatedByName(String userId) {
		return userInfoService.findById(userId)
				.map(UserInfo::getUsername)
				.orElse("Unknown");
	}

	public void insert(PortalFaqUI portalFaqUI) {
		portalFaqUI.setFaqAnswer(StringEscapeUtils.unescapeHtml(portalFaqUI.getFaqAnswer()));
		PortalFaq portalFaq = portalFaqUIMapper.toEntity(portalFaqUI);
		portalFaq.setId(null);
		portalFaqService.save(portalFaq);
	}

	public void update(PortalFaqUI portalFaqUI) {
		portalFaqUI.setFaqAnswer(StringEscapeUtils.unescapeHtml(portalFaqUI.getFaqAnswer()));
		PortalFaq portalFaq = portalFaqService.getById(portalFaqUI.getId());
		portalFaqUIMapper.updateToEntity(portalFaqUI, portalFaq);
		portalFaqService.save(portalFaq);
	}

	public void delete(String id) {
		portalFaqService.deleteById(id);
	}

}
