package ru.yandex.webmaster3.storage.checklist.dao;

import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.checklist.data.SiteProblemState;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.checklist.data.RecentlySentProblemNotification;
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;

/**
 * @author ishalaru
 * Таблица с TTL по sent_date на 2 дня
 */
@Repository
public class RecentlySentChecklistNotificationsYDao extends AbstractYDao {

    public RecentlySentChecklistNotificationsYDao() {
        super(PREFIX_CHECKLIST, "recently_sent_checklist_notifications");
    }

    public void addNotificationRecord(WebmasterHostId hostId, SiteProblemTypeEnum type, SiteProblemState state, DateTime date) {
        upsert(
                F.HOST_ID.value(hostId),
                F.TYPE.value(type),
                F.STATE.value(state),
                F.SENT_DATE.value(date)
        ).execute();
    }

    public RecentlySentProblemNotification getLatestSentNotification(
            WebmasterHostId hostId, SiteProblemTypeEnum problemType, SiteProblemState state) {
        return select(MAPPER)
                .where(F.HOST_ID.eq(hostId))
                .and(F.TYPE.eq(problemType))
                .and(F.STATE.eq(state))
                .queryOne();
    }

    private static final DataMapper<RecentlySentProblemNotification> MAPPER = DataMapper.create(
            F.HOST_ID, F.TYPE, F.STATE, F.SENT_DATE, RecentlySentProblemNotification::new
    );

    private static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<SiteProblemTypeEnum> TYPE = Fields.intEnumField("type", SiteProblemTypeEnum.R);
        static final Field<DateTime> SENT_DATE = Fields.jodaDateTimeField("sent_date");
        static final Field<SiteProblemState> STATE = Fields.intEnumField("state", SiteProblemState.R);
    }
}
