package ru.yandex.webmaster3.storage.importanturls;

import java.util.List;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.util.FNVHash;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.importanturls.data.RecommendedUrl;
import ru.yandex.webmaster3.storage.util.clickhouse2.AbstractClickhouseDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.ClickhouseQueryContext;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.QueryBuilder;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.Where;

/**
 * @author avhaliullin
 */
public class RecommendedUrlsCHDao extends AbstractClickhouseDao {
    private static final String DATABASE = DB_WEBMASTER3_IMPORTANTURLS;
    private static final String TABLE_MERGED = "recommended_urls";

    public List<RecommendedUrl> listRecommendedUrls(WebmasterHostId hostId) {
        Where q = QueryBuilder.select(F.PATH, F.CLICKS, F.SHOWS)
                .from(DATABASE, TABLE_MERGED)
                .where(QueryBuilder.eq(F.HOST_ID, hostId.toString()));
        return getClickhouseServer().queryAll(getContext(hostId), q.toString(), chRow -> new RecommendedUrl(
                chRow.getString(F.PATH),
                chRow.getLong(F.CLICKS),
                chRow.getLong(F.SHOWS)
        ));
    }

    public long count(WebmasterHostId hostId){
        Where q = QueryBuilder.select()
                                .countAll()
                                .from(DATABASE, TABLE_MERGED)
                                .where(QueryBuilder.eq(F.HOST_ID, hostId.toString()));

        return getClickhouseServer().queryOne(getContext(hostId),q.toString(),chRow ->  chRow.getLongUnsafe(0)).orElse(0L);
    }

    private ClickhouseQueryContext.Builder getContext(WebmasterHostId hostId) {
        int shards = getClickhouseServer().getShardsCount();
        int shard = (int) (FNVHash.hash64Mod(IdUtils.toHostString(hostId, true, false, false), shards));
        return withShard(shard);
    }

    private static class F {
        static final String HOST_ID = "host_id";
        static final String PATH = "path";
        static final String CLICKS = "clicks";
        static final String SHOWS = "shows";
    }
}
