package ru.yandex.webmaster3.storage.user.settings;

import com.google.common.base.Preconditions;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.DataMapper;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author leonidrom
 */
@Repository
public class FrontendUserSettingsYDao extends AbstractYDao {
    public FrontendUserSettingsYDao() {
        super(PREFIX_USER, "frontend_user_settings");
    }
    
    public void updateValue(long userId, FrontendUserSettingsKey key, String value) {
        upsert(
                F.USER_ID.value(userId),
                F.KEY.value(key),
                F.LAST_UPDATE.value(DateTime.now()),
                F.VALUE.value(value)
        ).execute();
    }

    public void deleteForUser(long userId) {
        delete().where(F.USER_ID.eq(userId)).execute();
    }

    public String getValue(long userId, FrontendUserSettingsKey key)  {
        return select(F.VALUE)
                .where(F.USER_ID.eq(userId))
                .and(F.KEY.eq(key))
                .queryOne();
    }

    public Map<FrontendUserSettingsKey, String> getValues(long userId, Collection<FrontendUserSettingsKey> keys) {
        Preconditions.checkArgument(keys.size() <= YDB_SELECT_ROWS_LIMIT,
                "Collection size exceeds YDB limitation");

        var lst = select(MAPPER)
                .where(F.USER_ID.eq(userId))
                .and(F.KEY.in(keys))
                .queryForList();
        
        Map<FrontendUserSettingsKey, String> result = new HashMap<>();
        lst.forEach(q -> result.put(q.getLeft(), q.getRight()));

        return result;
    }

    private static class F {
        static final Field<Long> USER_ID = Fields.longField("user_id");
        static final Field<FrontendUserSettingsKey> KEY = Fields.stringEnumField("key", FrontendUserSettingsKey.R);
        static final Field<DateTime> LAST_UPDATE = Fields.jodaDateTimeField("last_update");
        static final Field<String> VALUE = Fields.stringField("value").makeOptional();
    }

    public static final DataMapper<Pair<FrontendUserSettingsKey, String>> MAPPER = DataMapper.create(F.KEY, F.VALUE, Pair::of);
}
