package com.uas.account.dao;

import java.util.List;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import com.uas.account.entity.Setting;

@Repository
public class SettingDaoImpl extends BaseDao implements SettingDao {

	@Override
	public Setting save(Setting setting) {
		int count = count("from ac$setting where key_=?", setting.getKey());
		if (count == 0) {
			jdbcTemplate.update("insert into ac$setting(description,key_,value_,deleteable) values (?,?,?,?)", setting.getDescription(),
					setting.getKey(), setting.getValue(), setting.getDeleteable());
		} else {
			jdbcTemplate.update("update ac$setting set description=?,value_=?,deleteable=? where key_=?", setting.getDescription(),
					setting.getValue(), setting.getDeleteable(), setting.getKey());
		}
		return setting;
	}

	@Override
	public void save(List<Setting> settings) {
		for (Setting setting : settings)
			save(setting);
	}

	@Override
	public Setting findOne(String key) {
		try {
			return jdbcTemplate.queryForObject(
					"select description,key_ as \"KEY\",value_ as \"VALUE\",deleteable from ac$setting where key_=?",
					new BeanPropertyRowMapper<Setting>(Setting.class), key);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public void delete(String key) {
		jdbcTemplate.update("delete from ac$setting where key_=?", key);
	}

	@Override
	public List<Setting> findAll() {
		try {
			return jdbcTemplate.query("select description,key_ as \"KEY\",value_ as \"VALUE\",deleteable from ac$setting order by key_",
					new BeanPropertyRowMapper<Setting>(Setting.class));
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

}
