package ru.yandex.webmaster3.storage.robotstxt;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.joda.time.DateTime;
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.DataMapper;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.ValueDataMapper;

/**
 * WMC-6417
 *
 * @author akhazhoyan 12/2018
 */
@Repository
public class RobotsTxtSentNotificationsYDao extends AbstractYDao {
    public RobotsTxtSentNotificationsYDao() {
        super(PREFIX_ROBOTS_TXT, "robots_txt_sent_notifications");
    }

    public Set<Pair<WebmasterHostId, Long>> getSentNotificationByTableId(DateTime tableId) {
        return new HashSet<>(select(MAPPER)
                .where(F.TABLE_DATE.eq(tableId))
                .queryForList(Pair.of(F.HOST_ID, Pair::getKey), Pair.of(F.USER_ID, Pair::getValue)));
    }

    public void batchInsert(Collection<Triple<WebmasterHostId, Long, DateTime>> items) {
        batchInsert(VALUE_MAPPER, items).execute();
    }

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


    private static final DataMapper<Pair<WebmasterHostId, Long>> MAPPER = DataMapper.create(
            F.HOST_ID, F.USER_ID, Pair::of
    );

    private static final ValueDataMapper<Triple<WebmasterHostId, Long, DateTime>> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.HOST_ID, Triple::getLeft),
            Pair.of(F.USER_ID, Triple::getMiddle),
            Pair.of(F.TABLE_DATE, Triple::getRight)
    );

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