package ru.yandex.webmaster3.storage.robotstxt;

import java.util.Collection;
import java.util.List;

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

/**
 * WMC-6417
 * @author akhazhoyan 11/2018
 */
@Repository
public class RobotsTxtHistoryYDao extends AbstractYDao {

    public RobotsTxtHistoryYDao() {
        super(PREFIX_ROBOTS_TXT, "robots_txt_history");
    }

    public List<Instant> getRobotsTxtUpdates(WebmasterHostId hostId) {
        return select(F.DATE_ADDED).where(F.HOST_ID.eq(hostId)).queryForList();
    }

    public String getRobotsTxtContent(WebmasterHostId hostId, Instant dateAdded) {
        return select(F.CONTENT)
                    .where(F.HOST_ID.eq(hostId))
                    .and(F.DATE_ADDED.eq(dateAdded))
                    .queryOne();
    }

    public void insert(WebmasterHostId hostId, Instant dateAdded, String content) {
        upsert(F.HOST_ID.value(hostId), F.DATE_ADDED.value(dateAdded), F.CONTENT.value(content))
                .execute();
    }

    public void batchInsert(Collection<RobotTxtInfo> robotTxtInfos) {
        batchInsert(VALUE_MAPPER, robotTxtInfos).execute();
    }

    public void delete(WebmasterHostId hostId) {
        delete().where(F.HOST_ID.eq(hostId)).execute();
    }

    public void delete(Collection<WebmasterHostId> hostIds) {
        if (hostIds.isEmpty()) {
            return;
        }

        delete().where(F.HOST_ID.in(hostIds)).execute();
    }

    public static final ValueDataMapper<RobotTxtInfo> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.HOST_ID, RobotTxtInfo::getHostId),
            Pair.of(F.DATE_ADDED, RobotTxtInfo::getDateAdded),
            Pair.of(F.CONTENT, RobotTxtInfo::getContent),
            Pair.of(F.TTL, ign -> DateTime.now())
    );


    private static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<Instant> DATE_ADDED = Fields.jodaInstantField("date_added");
        static final Field<String> CONTENT = Fields.stringField("content");
        static final Field<DateTime> TTL  = Fields.jodaDateTimeField("ttl");

    }
}
