package ru.yandex.webmaster3.storage.video;

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.function.Consumer;

/**
 * @author vsedaikina
 * 20.10.21
 */
@Repository
public class VideohostOffersHistoryYDao extends AbstractYDao {

    protected VideohostOffersHistoryYDao() {
        super(PREFIX_VIDEO, "videohost_offers_history");
    }

    public void insert(VideohostOffer vho) {
        upsert(
                F.HOST_URL.value(vho.getHostUrl()),
                F.OFFER_URL.value(vho.getOfferUrl()),
                F.STATUS.value(vho.getStatus()),
                F.ADD_DATE.value(vho.getAddDate()),
                F.ERROR.value(vho.getError()),
                F.COMMENTS.value(vho.getComments()),
                F.UPDATE_DATE.value(vho.getUpdateDate())
        ).execute();
    }

    public void forEach(Consumer<VideohostOffer> consumer) {
        streamReader(MAPPER, consumer);
    }

    public void deleteBefore(DateTime updateDate) {
        delete().where(F.UPDATE_DATE.lte(updateDate)).execute();
    }

    private static final DataMapper<VideohostOffer> MAPPER = DataMapper.create(
            F.HOST_URL,
            F.OFFER_URL,
            F.STATUS,
            F.ADD_DATE,
            F.ERROR,
            F.COMMENTS,
            F.UPDATE_DATE,
            VideohostOffer::new
    );

    private interface F {
        Field<String> HOST_URL = Fields.stringField("host_url");
        Field<String> OFFER_URL = Fields.stringField("offer_url").makeOptional();
        Field<OfferStatus> STATUS = Fields.stringEnumField("status", OfferStatus.R);
        Field<DateTime> ADD_DATE = Fields.jodaDateTimeField("add_date");
        Field<OfferErrorType> ERROR = Fields.stringEnumField("error", OfferErrorType.R).makeOptional();
        Field<String> COMMENTS = Fields.stringField("comment").makeOptional();
        Field<DateTime> UPDATE_DATE = Fields.jodaDateTimeField("update_date");
    }
}
