package ru.yandex.webmaster3.storage.clickhouse.replication.dao;

import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;
import ru.yandex.webmaster3.storage.clickhouse.replication.data.ClickhouseReplicationTaskGroup;
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 java.util.UUID;

/**
 * @author leonidrom
 */
@Repository
public class ClickhouseReplicationProgressYDao extends AbstractYDao {
    public ClickhouseReplicationProgressYDao() {
        super(PREFIX_IMPORTER, "clickhouse_replication_progress");
    }

    public void update(ClickhouseReplicationTaskGroup taskGroup, String tableName, String dc, int shard, Integer insertsCount, DateTime updateTime) {
        upsert(
                F.TASK_ID.value(taskGroup.getCommand().getReplicationTaskId()),
                F.DATABASE.value(taskGroup.getCommand().getDatabase()),
                F.TABLE_NAME.value(tableName),
                F.DC.value(dc),
                F.SHARD.value(shard),
                F.INSERTS_COUNT.value(insertsCount),
                F.LAST_UPDATE.value(updateTime)
        ).execute();
    }

    public void clearOldRecords(DateTime updateTime) {
        delete().where(F.LAST_UPDATE.lt(updateTime)).execute();
    }

    private interface F {
        Field<UUID> TASK_ID = Fields.uuidField("task_id");
        Field<String> DATABASE = Fields.stringField("database");
        Field<String> TABLE_NAME = Fields.stringField("table_name");
        Field<String> DC = Fields.stringField("dc");
        Field<Integer> SHARD = Fields.intField("shard");
        Field<Integer> INSERTS_COUNT = Fields.intField("inserts_count").makeOptional();
        Field<DateTime> LAST_UPDATE = Fields.jodaDateTimeField("last_update");
    }
}
