package ru.yandex.wmconsole.service;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.wmconsole.service.dao.TblDicUserSettingsDao;
import ru.yandex.wmconsole.service.dao.TblUserSerttingsMetaDao;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;

import java.util.List;
import java.util.Map;

/**
 * User: azakharov
 * Date: 21.02.14
 * Time: 17:04
 */
public class UserSettingsService {

    private TblDicUserSettingsDao tblDicUserSettingsDao;
    private TblUserSerttingsMetaDao tblUserSettingsMetaDao;

    public void saveSettings(long userId, String key, String value) throws InternalException {
        Integer keyId = tblDicUserSettingsDao.getKeyIdByName(key);
        if (keyId == null) {
            keyId = tblDicUserSettingsDao.insertKey(key);
            if (keyId == null) {
                throw new InternalException(InternalProblem.INTERNAL_PROBLEM, "unable to insert key " + key);
            }
        }
        tblUserSettingsMetaDao.insertUserSettings(userId, keyId, value);
    }

    public Map<String, String> getSettings(long userId, List<String> keyNames) throws InternalException {
        if (keyNames.isEmpty()) {
            return tblUserSettingsMetaDao.getUserSettings(userId);
        } else {
            return tblUserSettingsMetaDao.getUserSettings(userId, keyNames);
        }
    }

    @Required
    public void setTblDicUserSettingsDao(TblDicUserSettingsDao tblDicUserSettingsDao) {
        this.tblDicUserSettingsDao = tblDicUserSettingsDao;
    }

    @Required
    public void setTblUserSettingsMetaDao(TblUserSerttingsMetaDao tblUserSettingsMetaDao) {
        this.tblUserSettingsMetaDao = tblUserSettingsMetaDao;
    }
}
