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

import java.util.List;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.storage.clickhouse.ClickhouseTableInfo;
import ru.yandex.webmaster3.storage.clickhouse.TableProvider;
import ru.yandex.webmaster3.storage.clickhouse.TableType;
import ru.yandex.webmaster3.storage.mirrors.dao.MainMirrorsCHDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.AbstractClickhouseDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.CHPrimitiveType;
import ru.yandex.webmaster3.storage.util.clickhouse2.CHTable;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.QueryBuilder;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.Where;

/**
 * Created by Oleg Bazdyrev on 19/02/2021.
 */
@Repository
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TurboAutoDeletedPagesCHDao extends AbstractClickhouseDao {

    public static final CHTable TABLE = CHTable.builder()
            .database(DB_WEBMASTER3_TURBO)
            .name("turbo_auto_deleted_pages_%s")
            .partitionBy("toYYYYMM(date)")
            .keyField(MainMirrorsCHDao.F.DATE, CHPrimitiveType.Date)
            .keyField(F.DOMAIN, CHPrimitiveType.String)
            .field(F.URL, CHPrimitiveType.String)
            .build();

    private final TableProvider tableStorage;

    public List<String> getUrls(String domain) {
        ClickhouseTableInfo table = tableStorage.getTable(TableType.TURBO_AUTO_DELETED_PAGES);
        Where st = QueryBuilder.select(F.URL).from(table.getTableName()).where(QueryBuilder.eq(F.DOMAIN, domain));

        return getClickhouseServer().queryAll(table.chContext(getClickhouseServer(), domain), st.toString(),
                chRow -> chRow.getString(0));
    }

    public interface F {
        String DATE = "date";
        String DOMAIN = "domain";
        String URL = "url";
    }

}
