package ru.yandex.webmaster3.storage.feeds.statistics;

import java.util.List;

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

import ru.yandex.webmaster3.core.feeds.feed.NativeFeedType;
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.OrderBy;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.QueryBuilder;

/**
 * Created by Oleg Bazdyrev on 30/03/2022.
 */
@Repository
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FeedsEnrichedShowsCHDao extends AbstractClickhouseDao {

    public static final String TABLE_NAME = "feeds_enriched_shows";
    public static final CHTable TABLE = CHTable.builder()
            .database(DB_WEBMASTER3_FEEDS)
            .name("tmp_" + TABLE_NAME + "_%s")
            .partitionBy("toYYYYMM(date)")
            .sharded(true)
            .keyField(F.DATE, CHPrimitiveType.Date)
            .keyField(F.DOMAIN, CHPrimitiveType.String)
            .keyField(F.TYPE, CHPrimitiveType.String)
            .field(F.URL, CHPrimitiveType.String)
            .field(F.SHOWS, CHPrimitiveType.Int64)
            .build();

    public List<UrlShows> getTopShows(String domain, NativeFeedType type, LocalDate from, LocalDate to, int page, int pageSize) {
        var q = QueryBuilder.select(F.URL, QueryBuilder.sum(F.SHOWS).toString())
                .from(DB_WEBMASTER3_FEEDS, TABLE_NAME)
                .where(QueryBuilder.eq(F.DOMAIN, domain))
                .and(QueryBuilder.eq(F.TYPE, type))
                .and(QueryBuilder.gte(F.DATE, from))
                .and(QueryBuilder.lte(F.DATE, to))
                .groupBy(F.URL)
                .orderBy(QueryBuilder.sum(F.SHOWS).toString(), OrderBy.Direction.DESC)
                .limit(page * pageSize, pageSize);
        return getClickhouseServer().queryAll(chContext(domain), q, chRow -> new UrlShows(chRow.getString(0), chRow.getLong(1)));
    }

    private interface F {
        String DATE = "date";
        String DOMAIN = "domain";
        String URL = "url";
        String TYPE = "type";
        String SHOWS = "shows";
    }

}
