package ru.yandex.webmaster3.viewer.http.searchquery.recommended.download;

import com.google.common.base.Charsets;
import com.google.common.hash.Funnel;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.blackbox.service.BlackboxUsersService;
import ru.yandex.webmaster3.core.data.L10nEnum;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.worker.task.WorkerTaskData;
import ru.yandex.webmaster3.storage.recommendedquery.download.DownloadRecommendedQueriesTaskData;
import ru.yandex.webmaster3.storage.recommendedquery.filtres.RecommendedQueryFilter;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;
import ru.yandex.webmaster3.viewer.http.download.DownloadAction;
import ru.yandex.webmaster3.viewer.http.searchquery.recommended.GetRecommendedQueryInfoAction;

/**
 * Created by ifilippov5 on 20.03.17.
 */
@ReadAction
@Description("Выгрузка рекомендованных запросов")
@Category("recommended")
public class DownloadRecommendedQueriesAction extends DownloadAction<DownloadRecommendedQueriesRequest> {
    private static final Logger log = LoggerFactory.getLogger(DownloadRecommendedQueriesAction.class);
    private final BlackboxUsersService blackboxExternalYandexUsersService;

    @Autowired
    public DownloadRecommendedQueriesAction(BlackboxUsersService blackboxExternalYandexUsersService) {
        this.blackboxExternalYandexUsersService = blackboxExternalYandexUsersService;
    }

    @Override
    protected WorkerTaskData getTaskData(DownloadRecommendedQueriesRequest request, long hash) {
        String fileName = generateFileName(request, hash);
        Condition condition = GetRecommendedQueryInfoAction.makeCondition(request.getParameterFilters(), request.getRegionId());
        L10nEnum lang = blackboxExternalYandexUsersService.getUserLanguage(request.getUserId()).orElse(L10nEnum.RU);
        return DownloadRecommendedQueriesTaskData.createTaskData(
                request.getHostId(),
                condition,
                request.getRegionId(),
                request.getOrderBy(),
                request.getOrderDirection(),
                request.getExportFormat(),
                fileName,
                hash,
                lang,
                request.getInclude()
        );
    }

    @Override
    protected long getHash(DownloadRecommendedQueriesRequest request) {
        HashFunction hf = Hashing.md5();

        Hasher hc = hf.newHasher()
                .putInt(request.getHostId().hashCode())
                .putString(request.getExportFormat().toString(), Charsets.UTF_8);

        if (request.getRegionId() != null)
            hc.putLong(request.getRegionId());

        if (request.getParameterFilters() != null) {
            for (RecommendedQueryFilter filter : request.getParameterFilters()) {
                hc.putObject(filter, (Funnel<RecommendedQueryFilter>) (recommendedQueryFilter, into) -> {
                    into.putString(recommendedQueryFilter.getOperation().toString(), Charsets.UTF_8);
                    into.putString(recommendedQueryFilter.getIndicator().toString(), Charsets.UTF_8);
                    into.putString(recommendedQueryFilter.getValue(), Charsets.UTF_8);
                });
            }
        }
        hc.putString(request.getInclude().name(), Charsets.UTF_8);
        hc.putString(request.getOrderBy().name(), Charsets.UTF_8);
        hc.putString(request.getOrderDirection().name(), Charsets.UTF_8);

        return hc.hash().asLong();
    }
}
