package com.eactive.eai.rms.data.entity.onl.code;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.common.spring.LocaleMessage;

@Service
@Transactional
public class CodeService extends AbstractDataService<Code, CodeId, CodeRepository> {

	@Autowired
	private LocaleMessage localeMessage;

	public List<Code> findByIdCodegroup(String codegroup) {
		return repository.findByIdCodegroupAndUseynOrderBySeq(codegroup, "Y");
	}

	public List<Code> findByCodeGroup(String searchCodeGroup) {
		Iterable<Code> codes = repository.findAll(QCode.code.id.codegroup.eq(searchCodeGroup),
				Sort.by("seq", "id.code"));
		return StreamSupport.stream(codes.spliterator(), false).collect(Collectors.toList());
	}

	public Optional<String> findCodeName(String codegroup, String code) {
		String language = localeMessage.getLocale().getLanguage();
		return repository.findById(new CodeId(codegroup, code)).map(entity -> entity.getCodeName(language));
	}

	public String getTranTypeCode(String code) {
		return this.findCodeName("TRAN_TYPE", code).orElse(null);
	}

	public Iterable<Code> findAllCodeGroup(String codegroup) {
		return repository.findAll(QCode.code.id.codegroup.eq(codegroup));
	}

	public void deleteByIdCodeGroup(String codegroup) {
		findAllCodeGroup(codegroup).forEach(this::delete);
	}

}
