package ru.yandex.wmconsole.service;


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

/**
 * Сохранения ошибок JavaScript и управления их логгированием
 *
 * User: azakharov
 * Date: 29.12.12
 * Time: 18:13
 */
public class LogErrorService extends AbstractDbService {

    private static final String INSERT_ERROR_MESSAGE_QUERY =
            "INSERT INTO tbl_error_log (user_id, date, browser, message) VALUES (?, NOW(), ?, ?)";

    private static final String SELECT_LOG_ENABLED_QUERY =
            "SELECT enabled FROM tbl_error_log_options WHERE user_id = ?";

    private static final String REPLACE_LOG_ENABLED_QUERY =
            "REPLACE INTO tbl_error_log_options (user_id, enabled) VALUES (?, ?)";

    public void logError(long userId, String browser, String message) throws InternalException {
        if (!logEnabled(userId)) {
            return;
        }
        getJdbcTemplate(WMCPartition.nullPartition()).update(
                INSERT_ERROR_MESSAGE_QUERY, userId, browser, message);
    }

    public boolean logEnabled(long userId) throws InternalException {
        Boolean res = getJdbcTemplate(WMCPartition.nullPartition()).safeQueryForObject(
                SELECT_LOG_ENABLED_QUERY, new BooleanRowMapper(), userId);
        return res != null ? res : false;
    }

    public void saveLogEnabled(long userId, boolean enabled) throws InternalException {
        getJdbcTemplate(WMCPartition.nullPartition()).update(
                REPLACE_LOG_ENABLED_QUERY, userId, enabled);
    }
}
