package ru.yandex.webmaster3.storage.delegation;

import java.util.List;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;

/**
 * Created by ifilippov5 on 08.01.18.
 */
@Repository
public class UserDelegationsForSendYDao extends AbstractYDao {

    public UserDelegationsForSendYDao() {
        super(PREFIX_DELEGATION, "user_delegations_for_send");
    }

    public void add(long toUser, WebmasterHostId hostId) {
        upsert(
                F.USER_ID.value(toUser),
                F.HOST_ID.value(hostId)
        ).execute();
    }

    public List<Long> getAll() {
        return selectDistinct(F.USER_ID)
                .queryForList(Pair.of(F.USER_ID, x -> x));
    }

    public void delete(List<Long> userIds) {
        delete()
                .where(F.USER_ID.in(userIds))
                .execute();
    }

    public void delete(long toUser, WebmasterHostId hostId) {
        delete()
                .where(F.USER_ID.eq(toUser))
                .and(F.HOST_ID.eq(hostId))
                .execute();
    }

    public boolean contains(long toUser, WebmasterHostId hostId) {
        return select(F.USER_ID)
                .where(F.USER_ID.eq(toUser))
                .and(F.HOST_ID.eq(hostId))
                .queryOne() != null;
    }

    private static class F {
        static final Field<Long> USER_ID = Fields.longField("user_id");
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
    }
}
