package ru.yandex.webmaster.common.host.dao;

import java.util.List;

import ru.yandex.common.util.db.LongRowMapper;
import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.service.AbstractDbService;

/**
 * @author aherman
 */
public class TblUsersHostsCounterDao extends AbstractDbService {
    public List<Long> getCount(long userId) throws InternalException {
        String q = "SELECT count FROM tbl_users_hosts_counter WHERE user_id = ?";
        return getJdbcTemplate(WMCPartition.nullPartition()).query(q, new LongRowMapper(), userId);
    }

    public void increaseCounter(long userId, int delta) throws InternalException {
        String q = String.format("UPDATE tbl_users_hosts_counter SET count = count + %d WHERE user_id = ?" , delta);
        getJdbcTemplate(new WMCPartition(null, null, userId)).update(q, userId);
    }

    public void insertOrIncreaseCounter(long userId, int delta) throws InternalException {
        String q = String.format(
                "INSERT INTO tbl_users_hosts_counter (user_id, count) VALUES (?, %1$d) ON DUPLICATE KEY UPDATE count = count + %1$d", delta);
        getJdbcTemplate(new WMCPartition(null, null, userId)).update(q, userId);

    }

    public void decreaseCounter(long userId) throws InternalException {
        String q = "UPDATE tbl_users_hosts_counter SET count = count - 1 WHERE user_id = ?";
        getJdbcTemplate(WMCPartition.nullPartition()).update(q, userId);
    }

    public void insertOrDecreaseCounter(long userId) throws InternalException {
        String q = "INSERT INTO tbl_users_hosts_counter (user_id, count) VALUES (?, -1) ON DUPLICATE KEY UPDATE count = count - 1";
        getJdbcTemplate(WMCPartition.nullPartition()).update(q, userId);
    }
}
