package com.uas.account.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.uas.account.AccountConfig;
import com.uas.account.core.Const;
import com.uas.account.dao.AppDao;
import com.uas.account.entity.App;
import com.uas.account.entity.App.Scope;
import com.uas.account.exception.VisibleError;
import com.uas.account.viewmodel.AppUseView;
import com.uas.account.viewmodel.AppView;

@Service
public class AppServiceImpl implements AppService {

	@Autowired
	private AppDao appDao;

	@Override
	@CacheEvict(value = "apps", key = "#app.uid")
	public App save(App app) {
		if (!StringUtils.isEmpty(app.getUserControl())) {
			App control = appDao.findOne(app.getUserControl());
			if (control == null) {
				throw new VisibleError("应用" + app.getUserControl() + "不存在");
			} else {
				app.setBackSpaceUrl(null);
				app.setBackUserUrl(null);
				app.setCopyApps(null);
				app.setEncryFormat(null);
				app.setPublicKey(null);
				app.setScope(control.getScope());
				// no register
				app.setDefaultUse(Const.NO);
			}
		}
		if (app.getScope() == null) {
			app.setScope(Scope.PRIVATE.name());
		}
		if (app.getDefaultUse() == null || AccountConfig.ACCOUNT_CENTER.equals(app.getUid())) {
			app.setDefaultUse(Const.NO);
		}
		if (null == app.getDialectEnable()) {
			app.setDialectEnable(Const.NO);
		}
		return appDao.save(app);
	}

	@Override
	public List<String> findAllIDs() {
		return appDao.findAllIDs();
	}

	@Override
	public List<String> findAllIDsByUser(long userId) {
		return appDao.findAllIDsByUser(userId);
	}

	@Override
	@Cacheable(value = "apps")
	public App findOne(String uid) {
		return appDao.findOne(uid);
	}

	@Override
	public List<App> findAll() {
		return appDao.findAll();
	}

	@Override
	@CacheEvict(value = "apps")
	public void delete(String uid) {
		App app = appDao.findOne(uid);
		if (app != null) {
			if (app.getUsCount() > 0) {
				throw new VisibleError("该应用已被启用，无法删除！");
			} else {
				appDao.delete(uid);
			}
		}
	}

	@Override
	public List<AppView> findAllView() {
		return appDao.findAllView();
	}

	@Override
	public List<AppUseView> findAllPublicUseView() {
		return appDao.findAllPublicUseView();
	}
}
