package com.keao.edu.user.service.impl;

import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.entity.SysConfig;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.user.dao.ShortUrlDao;
import com.keao.edu.user.entity.ShortUrl;
import com.keao.edu.user.service.ShortUrlService;
import com.keao.edu.user.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShortUrlServiceImpl extends BaseServiceImpl<Long, ShortUrl> implements ShortUrlService {
	
	@Autowired
	private ShortUrlDao shortUrlDao;
	@Autowired
	private SysConfigService sysConfigService;

	@Override
	public BaseDAO<Long, ShortUrl> getDAO() {
		return shortUrlDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String createShortUrl(String sourceUrl) {
		if(StringUtils.isBlank(sourceUrl)){
			return sourceUrl;
		}
		ShortUrl shortUrl=new ShortUrl(sourceUrl);
		shortUrlDao.insert(shortUrl);

		SysConfig baseUrlConfig = sysConfigService.findByParamName(SysConfigService.BASE_API_URL);

		StringBuffer returnUrl=new StringBuffer(baseUrlConfig.getParanValue());
		returnUrl.append("/api-user/su/");
		returnUrl.append(shortUrl.getId());

		return returnUrl.toString();
	}
}
