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

import java.util.List;

import com.google.common.collect.Iterables;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.storage.importer.model.ImportDefinition;
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;

/**
 * Created by Oleg Bazdyrev on 02/10/2020.
 */
@Repository
public class ClickhouseImportDefinitionsYDao extends AbstractYDao {

    private static final String TABLE_NAME = "clickhouse_import_definitions";

    public ClickhouseImportDefinitionsYDao() {
        super(PREFIX_IMPORTER, TABLE_NAME);
    }

    public void update(ImportDefinition definition, boolean isFromFile) {
        execute(upsert(F.ID.value(definition.getId()), F.IS_FROM_FILE.value(isFromFile), F.DEFINITION.value(definition)));
    }

    public ImportDefinition get(String id) {
        return queryOne(select(F.DEFINITION).where(F.ID.eq(id)).getStatement(), F.DEFINITION);
    }

    public List<ImportDefinition> listAll() {
        return queryForList(select(F.DEFINITION).order(F.ID.asc()), F.DEFINITION, (list) ->
                select(F.DEFINITION).where(F.ID.gt(Iterables.getLast(list).getId())).order(F.ID.asc()));
    }

    public interface F {
        Field<String> ID = Fields.stringField("id");
        Field<Boolean> IS_FROM_FILE = Fields.boolField("is_from_file");
        Field<ImportDefinition> DEFINITION = Fields.jsonField2("definition", ImportDefinition.class);
    }
}
