package com.eactive.eai.rms.onl.manage.authserver.scope;

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;

import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.spring.LocaleMessage;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeEntityService;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeInfo;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeInfoService;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeSearch;
import com.eactive.eai.rms.onl.common.exception.BizException;

@Service
@Transactional
public class ScopeManService extends OnlBaseService {

	private ScopeInfoService scopeInfoService;

	private ScopeEntityService scopeEntityService;
	
	private ScopeUIMapper scopeUIMapper;

	private LocaleMessage localeMessage;
	
	@Autowired
	public ScopeManService(ScopeInfoService scopeInfoService, ScopeEntityService scopeEntityService, 
			ScopeUIMapper scopeUIMapper, LocaleMessage localeMessage ) {
		this.scopeInfoService = scopeInfoService;
		this.scopeEntityService = scopeEntityService;
		this.scopeUIMapper = scopeUIMapper;
		this.localeMessage = localeMessage;
	}

	public Page<ScopeUI> selectList(Pageable pageable, ScopeSearch scopeSearch) {
		Page<ScopeInfo> page = scopeInfoService.findAll(pageable, scopeSearch);
		return page.map(scopeUIMapper::toVo);
	}

	public ScopeUI selectDetail(String scopeId) {
		return scopeUIMapper.toVo(scopeInfoService.getById(scopeId));
	}

	public void insert(ScopeUI scopeUI) {
		if(scopeInfoService.existsById(scopeUI.getScopeId())) {
			throw new BizException(localeMessage.getString("scpMan.scpIdExists"));
		}
		ScopeInfo scopeInfo = scopeUIMapper.toEntity(scopeUI);
		scopeInfoService.save(scopeInfo);
	}

	public void update(ScopeUI scopeUI) {
		ScopeInfo scopeInfo = scopeInfoService.getById(scopeUI.getScopeId());
		scopeUIMapper.updateToEntity(scopeUI, scopeInfo);
		scopeInfoService.save(scopeInfo);
	}

	public void delete(String scopeId) {
		scopeInfoService.deleteById(scopeId);
	}
	
	public void deleteApiScopeRelationsByScopeId(String scopeId) {
		scopeEntityService.deleteByIdScopeId(scopeId);
	}
	
}
