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

import java.util.Collection;

import lombok.Getter;
import lombok.Value;
import org.apache.commons.lang3.tuple.Pair;
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 ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.ValueDataMapper;

/**
 * Created by Oleg Bazdyrev on 2019-07-17.
 */
@Repository
public class TurboAutoparsedHostsSpeedsYDao extends AbstractYDao {

    private static final DataMapper<OwnerSpeedInfo> MAPPER = DataMapper.create(
            F.OWNER, F.NON_TURBO_SPEED, F.TURBO_SPEED, F.UPDATE_DATE, OwnerSpeedInfo::new);

    private static final ValueDataMapper<OwnerSpeedInfo> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.OWNER, OwnerSpeedInfo::getOwner),
            Pair.of(F.NON_TURBO_SPEED, OwnerSpeedInfo::getNonTurboSpeed),
            Pair.of(F.TURBO_SPEED, OwnerSpeedInfo::getTurboSpeed),
            Pair.of(F.UPDATE_DATE, OwnerSpeedInfo::getUpdateDate)
    );

    public TurboAutoparsedHostsSpeedsYDao() {
        super(PREFIX_TURBO, "turbo_autoparsed_hosts_speeds");
    }

    public void insert(Collection<OwnerSpeedInfo> data) {
        batchInsert(VALUE_MAPPER, data).execute();
    }

    public OwnerSpeedInfo getSpeed(String domain) {
        return select(MAPPER).where(F.OWNER.eq(domain)).queryOne();
    }

    private interface F {
        Field<String> OWNER = Fields.stringField("owner");
        Field<Double> NON_TURBO_SPEED = Fields.doubleField("non_turbo_speed").makeOptional();
        Field<Double> TURBO_SPEED = Fields.doubleField("turbo_speed").makeOptional();
        Field<DateTime> UPDATE_DATE = Fields.jodaDateTimeField("update_date");
    }

    @Getter
    @Value
    public static class OwnerSpeedInfo {
        String owner;
        Double nonTurboSpeed;
        Double turboSpeed;
        DateTime updateDate;
    }
}
