package com.uas.account.service;

import java.util.ArrayList;
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 com.uas.account.core.Page;
import com.uas.account.dao.AssetDao;
import com.uas.account.entity.Asset;
import com.uas.account.viewmodel.AssetView;

@Service
public class AssetServiceImpl implements AssetService {

	@Autowired
	private AssetDao assetDao;

	@Override
	@CacheEvict(value = "assets", allEntries = true)
	public Asset save(Asset asset) {
		if (null == asset.getIdx() || asset.getIdx() <= 0) {
			asset.setIdx(assetDao.countByApp(asset.getAppId()) + 1);
		}
		if (asset.getBackground() == null) {
			asset.setBackground("transparent");
		}
		if (asset.getColor() == null) {
			asset.setColor("inherit");
		}
		if (asset.getReserveColor() == null) {
			asset.setReserveColor(asset.getColor());
		}
		return assetDao.save(asset);
	}

	@Override
	@Cacheable(value = "assets", key = "'appId:'+#appId")
	public List<AssetView> findByApp(String appId) {
		List<Asset> assets = assetDao.findByApp(appId);
		List<AssetView> assetViews = null;
		if (assets != null) {
			assetViews = new ArrayList<AssetView>();
			for (Asset asset : assets) {
				// convert to https
				asset.setUrl(asset.getUrl().replace("http://", "https://"));
				assetViews.add(new AssetView(asset));
			}
		}
		return assetViews;
	}

	@Override
	@CacheEvict(value = "assets", key = "'appId:'+#asset.appId")
	public void delete(Asset asset) {
		assetDao.delete(asset);
	}

	@Override
	public Page<Asset> findAll(String appId, int pageNumber, int pageSize) {
		return assetDao.findAll(appId, pageNumber, pageSize);
	}

	@Override
	public Asset findOne(Long id) {
		return assetDao.findOne(id);
	}

}
