package ru.yandex.webmaster3.storage.turbo.dao.autoparser;

import java.util.Collection;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.Value;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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;


/**
 * Created by Oleg Bazdyrev on 2019-08-12.
 */
@Repository
public class TurboAutoparserScreenshotsYDao extends AbstractYDao {

    @Autowired
    public TurboAutoparserScreenshotsYDao() {
        super(PREFIX_TURBO, "turbo_autoparser_screenshots");
    }

    private static final ValueDataMapper<TurboAutoparserScreenshot> VALUE_DATA_MAPPER = ValueDataMapper.create2(
            Pair.of(F.URL, TurboAutoparserScreenshot::getUrl),
            Pair.of(F.SCREENSHOT, TurboAutoparserScreenshot::getScreenshot),
            Pair.of(F.DETAILS, TurboAutoparserScreenshot::getDetails),
            Pair.of(F.DURATION, TurboAutoparserScreenshot::getDuration),
            Pair.of(F.UPDATE_DATE, TurboAutoparserScreenshot::getUpdateDate)
    );

    public void addScreenshots(Collection<TurboAutoparserScreenshot> screenshots) {
        batchInsert(VALUE_DATA_MAPPER, screenshots).execute();
    }

    public String getScreenshot(String url) {
        return select(F.SCREENSHOT).where(F.URL.eq(url)).queryOne();
    }

    @Value
    public static class TurboAutoparserScreenshot {
        String url;
        String screenshot;
        JsonNode details;
        JsonNode duration;
        DateTime updateDate;
    }

    private interface F {
        Field<String> URL = Fields.stringField("url");
        Field<String> SCREENSHOT = Fields.stringField("screenshot");
        Field<JsonNode> DETAILS = Fields.jsonField2("details", JsonNode.class).makeOptional();
        Field<JsonNode> DURATION = Fields.jsonField2("duration", JsonNode.class).makeOptional();
        Field<DateTime> UPDATE_DATE = Fields.jodaDateTimeField("update_date");
    }
}
